全栈工程师开发手册 (作者:栾鹏)
安卓自定义控件:包含LinearLayout、RelativeLayout、GridView、Button等
本文以LinearLayout为例
首先要有一个自定义xml布局文件
我们这里存储下面的代码为ui_linearlayout.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/ui_linearlayout_editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="4"
/>
<Button
android:id="@+id/ui_linearlayout_clearButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="搜索"
android:layout_weight="1"
/>
</LinearLayout>
自定义控件继承自LinearLayout
在自定义控件的绑定布局文件,并进行相应的ui初始化,添加自定义的属性和方法。
//自定义组合控件
public class UI_LinearLayout extends LinearLayout{
private View view;
private LayoutInflater layoutInflater;
private EditText editText;
private Button clearButton;
public UI_LinearLayout(Context context) { //自己定义构造函数,可以传递想要的数据进来
super(context);
//使用布局资源填充视图
String infService = Context.LAYOUT_INFLATER_SERVICE;
layoutInflater = (LayoutInflater)getContext().getSystemService(infService); //layoutInflater=LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.ui_linearlayout, this, true); //获取当前控件的引用,使用this也行
//获取对子控件的引用
editText = (EditText)findViewById(R.id.ui_linearlayout_editText);
clearButton = (Button)findViewById(R.id.ui_linearlayout_clearButton);
//也可以使用代码自己添加
}
//组合控件的自定义函数
private void fun1(String str,Drawable Images,OnClickListener onclick){
editText.setText(str);
clearButton.setBackgroundDrawable(Images);
clearButton.setOnClickListener(onclick);
}
在activity中添加自定义控件
RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.activity1_relativeLayout1);
UI_LinearLayout myview = new UI_LinearLayout(this);
relativeLayout .addView(myview);
//myview.fun1(str, Images, onclick); //调用内部函数