情景:
有兩個個佈局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。