创建自定义控件可以解决重复编写布局代码的问题。
比如说QQ标题栏中的返回按钮,不管是在哪一个活动中,这个按钮的功能都是相同的,即销毁掉当前活动。而如果在每一个活动中都需要重新注册一遍返回按钮的点击事件,明显地增加了很多重复代码,这种情况最好是使用自定义控件的方式来解决。
下面写一个最简单的自定义标题栏,代码如下:
1.新建一个布局 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="@color/colorPrimary"
android:orientation="horizontal">
<Button
android:id="@+id/title_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:text="返回"
android:textColor="#fff" />
<TextView
android:id="@+id/title_text"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:text="与郭峰对话中..."
android:textSize="24sp" />
<Button
android:id="@+id/title_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dip"
android:text="更多"
android:textColor="#fff" />
</LinearLayout>
2.新建 TitleLayout 继承自 LinearLayout,让它成为自定义的标题栏控件。
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);
Button titleBack = (Button) findViewById(R.id.title_back);
Button titleEdit = (Button) findViewById(R.id.title_edit);
titleBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity) getContext()).finish();
}
});
titleEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "更多", Toast.LENGTH_SHORT).show();
}
});
}
}
首先:重写了 LinearLayout中的带有两个参数的构造函数,在布局中引入 TitleLayout 控件就会调用这个构造函数。
然后:在构造函数中借助 LayoutInflater对标题栏布局进行动态加载,通过 LayoutInflater的 from()方法可以构建出一个 LayoutInflater 对象,然后调用 inflate()方法就可以动态加载一个布局文件,inflate()方法接收两个参数:
第一个参数是要加载的布局文件的 id,传入第一步写好的title.xml。
第二个参数是给加载好的布局再添加一个父布局,直接传入 this。
最后:添加了按钮的点击监听事件...
3.添加自定义控件
通过上面两步,自定义控件已经创建好了,然后在布局文件activity_main.xml中添加代码:
<com.guofeng.demo5.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.guofeng.demo5.TitleLayout>
添加自定义控件和添加普通控件的方式基本是一样的,只不过在添加自定义控件的时候我们需要指明控件的完整类名,包名在这里是不可以省略的。
这样,一个最基本的自定义标题栏就弄好了,省去了很多编写重复代码的工作~~~