记这两天写代码遇到的一个坑…
标题栏是大家做界面的时候都用的一个东西,我在做项目的时候在基类里面封装了一个基于Toolbar的标题栏,由子页面继承并初始化设置标题栏,挺简单的一个东西,直到出现了以下情况….
使用场景是这样的:实现类的布局是RelativeLayout布局,标题栏下面的控件用到了layout_below这个属性设置,然后我就给include加了个id,好,到此为止,一切很完美…那么问题来了,当我在代码里初始化标题栏的时候,标题栏的根布局,也就是Toolbar不想跟我说话,并向我扔了个空指针异常….此时此刻我的内心几乎是崩溃的!
然后就有了今天这篇博客,下面我模拟了一下上述的使用场景,首先是一个简易的标题栏,布局如下:
<?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="48dp"
android:id="@+id/ll_view"
android:gravity="center_vertical"
android:background="@color/colorPrimary"
android:orientation="horizontal">
<Button
android:id="@+id/btn_left"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left|center_vertical"
android:paddingLeft="20dp"
android:background="@android:color/transparent"
android:textColor="@android:color/white"
android:text="返回"/>
<TextView
android:id="@+id/tv_content"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:background="@android:color/transparent"
android:textColor="@android:color/white"
android:text="主页"/>
<Button
android:id="@+id/btn_right"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="right|center_vertical"
android:paddingRight="20dp"
android:background="@android:color/transparent"
android:textColor="@android:color/white"
android:text="更多"/>
</LinearLayout>
然后在layout_main里引入:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.liwy.nullviewtest.MainActivity">
<include
android:id="@+id/top"
layout="@layout/custom_layout"></include>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/top"
android:gravity="center"
android:text="Hello World!" />
</RelativeLayout>
好,下面开始初始化设置:
private LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout)findViewById(R.id.ll_view);
linearLayout.setBackgroundColor(Color.RED);
}
结果就是大大的空指针异常…
解决办法有两种:
第一种:把初始化这里改为findViewById(R.id.top),就可以正常运行。
第二种:在include外面在嵌套一层布局,也是可以正常运行的。
造成这种错误的原因就是include这里的属性设置会覆盖被引用布局父控件的属性,包括控件宽、高、id等。所以列为使用要谨记谨记……