创建每个Activity都有的布局,例如标题栏返回/标题/编辑都一样

/* 此处以创建一个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>




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值