/* 此处以创建一个APP中每个界面都有的顶上的“返回”“名称”“编辑”为例子 */
1. 在layout文件夹下新建一个title.xml代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="返回" />
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="标题" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="编辑" />
</LinearLayout>
(2). 在Activity对应的布局下引用title的布局。(如果用自定义控件,这句话可以不要)
<include layout="@layout/title" />
此处完成布局引用,再在java代码中设置按键事件。
3. 创建自定义控件
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) { //引用TitleLayout控件就会调用此构造方法
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this); //用LayoutInflater实现对标题栏布局进行动态加载
Button titleBack = (Button) findViewById(R.id.title_back);
titleBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
( (Activity) getContext() ).finish(); //finish()是Activity的方法,getContext()获取上下文,并转换为Activity类型
}
});
}
}
4. 添加自定义控件
与 <include layout="@layout/title" />显示的效果一样,但是include没有点击事件,因为没有对应的java书写点击事件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.uicustomviews.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>