如何创建一个自定义的控件,并且对其进行使用。
这里要创建一个自定义的标题栏,标题栏从左到右一共三个控件,Button、TextView、Button,如图:
第1步
首先在layout文件夹中新建一个title.xml,并添加如下代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#444444"
android:orientation="horizontal" >
<Button
android:id="@+id/title_exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#333333"
android:gravity="center"
android:text="Exit"
android:textColor="#DDDDDD" />
<TextView
android:id="@+id/title_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="Title Text"
android:textColor="#EEEEEE"
android:textSize="24sp" />
<Button
android:id="@+id/title_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#333333"
android:gravity="center"
android:text="Edit"
android:textColor="#DDDDDD" />
</LinearLayout>
第2步
新建TitleLayout.java,并且继承自LinearLayout
public class TitleLayout extends LinearLayout {
// 重写LinearLayout中带有两个参数的构造方法TitleLayout
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// 在构造方法中对标题栏布局动态加载,这就要借助LayoutInflater来实现了
// 通过LayoutInflater的from()方法构建一个LayoutInflater对象
// 然后调用inflater()动态加载一个布局文件,第一个参数是布局文件id
// 第二个参数给加载好的布局文件添加一个父布局,这里指定为TitleLayout,于是直接写this
LayoutInflater.from(context).inflate(R.layout.title, this);
}
}
第3步
在要添加自定义控件的布局文件中,添加以下代码,这里在activity_main.xml中添加
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<alex.example.uicustomviews.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</alex.example.uicustomviews.TitleLayout>
</LinearLayout>
添加自定义控件需要指明控件的完整类名,包名在这里不可以省略。
第4步
现在重新运行程序就可一个发现已经成功的使用了自定义控件。下面需要在自定义控件添加一些红能,这里给按钮添加上点击功能。在TitleLayout.java中添加如下代码:
public class TitleLayout extends LinearLayout {
Button btn_title_exit = null;
Button btn_title_edit = null;
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);
btn_title_exit = (Button) findViewById(R.id.title_exit);
btn_title_edit = (Button) findViewById(R.id.title_edit);
btn_title_exit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity) getContext()).finish();
}
});
btn_title_edit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "You clicked Edit Button",
Toast.LENGTH_SHORT).show();
}
});
}
这样以后想引用自定义控件,直接在相应界面小xml文件中添加就可以了(参考第3步)。