情景:
有两个个布局A和B,在A中的父控件是RelativeLayout,在B中 include A,我们想要拿到A中的这个RelativeLayout。
解法一:
如果B include A的时候没有设置ID,那么我们可以在A的RelativeLayout中添加一个ID,然后在Activity中获取这个id,得到的对象就是这个RelativeLayout的对象;
解法二:
如果B include A的时候设置了ID,那么我们再像方法一那样去找,就会返回null,我们要在findID的时候使用这个include的时候添加的这个id。
举个例子:
布局A:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rl_title_container"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@drawable/bg_title">
</RelativeLayout>
布局B:
<?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:orientation="vertical">
<include
layout="@layout/inc_title"//如果想直接获取A的RelativeLayout那就去掉它
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_gravity="top" />
</LinearLayout>
我们可以看到布局B中include的时候设置了Id inc_title
,所以我们在Activity中直接这样写就会返回null
rl_title_container = getView(R.id.rl_title_container);//这个id是A中的父控件ID
总结就是有这个inc_title
时我们就用这个inc_title
去找A的父控件,如果没有这个ID,那我们就像上面那样写,直接用A中的RelativeLayout的Id。