XML布局优化之一,include复用以及引用其某个控件ID进行监听

来源:互联网 发布:linux mint vim 编辑:程序博客网 时间:2024/06/05 04:13

为了方便以后自己的使用,整理了一点点xml布局的时候的一些小总结:
提供出来供大家一起使用:


< include>标签可以在一个布局中引入另外一个布局,这个的好处显而易见。类似于我们经常用到的工具类,随用随调。便于统一修改使用。


这里写图片描述


代码上图是效果图,具体代码:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="48dp"    android:background="@color/background">    <ImageView        android:id="@+id/imageView"        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:paddingLeft="15dp"        android:paddingRight="15dp"        android:src="@drawable/icon__back" />    <TextView        android:id="@+id/textView"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="标题"        android:textColor="@color/white"        android:textSize="18sp" />    <TextView        android:id="@+id/textView2"        android:layout_width="wrap_content"        android:layout_height="match_parent"        android:layout_alignParentRight="true"        android:gravity="center"        android:paddingLeft="15dp"        android:paddingRight="15dp"        android:text="保存"        android:textColor="@color/white"        android:textSize="16sp" /></RelativeLayout>

举例的效果图:

这里写图片描述

引用的时候直接在xml布局文件里调用:

这里写图片描述
代码:

    <include        android:id="@+id/include_head"        layout="@layout/include_head_infosetting"></include>

常用的分割线:

  <Space        android:layout_width="match_parent"        android:layout_height="15dp" />

那么引用了include标签后,布局里面的空间怎么监听呢? 这里也提供一个方法:

使用 include标签引入另一个布局文件

如何对include下的某个控件进行监听 如Button Image Button等
可通过findViewById来查找

第一步给引入的include标签 设置一个ID 用来查找此引入的布局文件,

其中example_include_id为我设置的ID 可自行更改
index为我需要引入的布局文件XML的名称

    private void initView() {        findViewById(R.id.include_head).findViewById(R.id.imageView).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {            }        });    }

这样进行添加按钮的监听事件。

0 0
原创粉丝点击