一款优秀的移动应用须要具备本身独特统一的风格,一般状况下UI设计师会根据产品需求和使用人群的特色,设计总体的风格,界面的元素和控件的互效果。而原生态的Android控件为开发人员提供的是最基本的积木元素,若是要准确地传递统一的视觉效果和交互体验,对控件的自定义使用是很是有必要的。前端
Android开发也采用前端xml+后端Java的形式进行页面开发,写过C#的人应该知道,xml是一种界面元素布局的直观显示,根据标签自动完成编译显示给用户,无需运行时才能看到界面,这样的分离能减少代码的耦合而且方便调试。但本质上去除xml布局文件,依然是能够完成全部的程序设计。这篇文章经过一个简单的彻底从Java后台程序中进行建立的示例来讲明Android自定义控件的运行原理。android
下面是一个简单的自定义控件,继承LinearLayout,加一个居中的ImageView和TextView。后端
private void initView(Context context){ setOrientation(VERTICAL); // 定义布局填充形式,该布局的宽和高均根据内容自适应调整 ViewGroup.LayoutParams wrap_wrapParams = new LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT); setLayoutParams(wrap_wrapParams); setGravity(Gravity.CENTER); LinearLayout.LayoutParams params = new LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); params.gravity = Gravity.CENTER; imageView = new ImageView(context); imageView.setId(10001); textView = new TextView(context); textView.setId(10002); addView(imageView, params); addView(textView, params); } /*设置显示文字*/ public void setTextViewText(String text){ textView.setText(text); }
若是要用xml进行描述以下:ide
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <!-- Display a button --> <ImageView android:id="@+id/icon_part" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" /> <!-- android:src="@drawable/ic_action_share" --> <TextView android:id="@+id/text_part" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"/> </LinearLayout>
调用的时候直接:布局