您的位置:首页 > 移动开发 > Android开发

关于android include标签使用的一点心得和疑惑

2016-09-30 12:15 573 查看
include标签用于复用已有的布局文件,使得一份布局文件可以在多个地方使用。

定义一个待复用的自定义标题栏布局文件

title_layout.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="match_parent"
android:id="@+id/title_layout_customize"
android:background="#135D61"
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="5dp"
android:gravity="center"
android:text="Back"
android:textColor="#841515" />

<TextView
android:id="@+id/textView1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="this is title"
android:textColor="#841515"
android:textSize="25sp" />

<Button
android:id="@+id/title_edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Edit"
android:textColor="#841515"
android:layout_gravity="center"/>

</LinearLayout>


需要使用这个自定义标题布局文件的主布局文件activity_custom.xml通过include标签引入

<include
<!--关于include标签width和height属性是必须要设置 -->
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/title_layout"/>


然后activity文件可以对include标签中的子控件进行设置属性

比如下面可以对title_layout.xml文件根节点title_layout_customize设置背景颜色。

linearLayout = (LinearLayout) findViewById(R.id.title_layout_customize);
linearLayout.setBackgroundColor(Color.RED);
back = (Button) findViewById(R.id.title_back);
edit = (Button) findViewById(R.id.title_edit);
tv_show = (TextView) findViewById(R.id.textView1);
back.setOnClickListener(this);
edit.setOnClickListener(this);


但我对include标签设置id属性后,上面对属性设置的代码就会报错说空指针异常。

这个时候需要先获取到title_layout.xml布局文件view,然后在通过这个view找到里面的子控件比如R.id.title_layout_customize,这就不会报空指针异常了。代码如下。但是有一个很遗憾的问题是虽然不会报错但是不能设置成功背景颜色。我不知道为什么,我在API19上面实践是这样的情况。请大神指教。

所以为了实现效果还是不对include标签设置id属性好。

layout = getLayoutInflater().inflate(R.layout.title_layout, null);
linearLayout = (LinearLayout) layout
.findViewById(R.id.title_layout_customize);
linearLayout.setBackgroundColor(Color.RED);


reference
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: