Access view of included xml layout

时光总嘲笑我的痴心妄想 提交于 2019-12-07 04:11:24

In b.xml, you should correct:

android:layout_below="@id/xyz"

to

android:layout_below="@id/a_layout"

And then you can use it in your code (Here I place it in onCreate):

setContentView(R.layout.b);    
((Button)findViewById(R.id.xyz)).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            ((TextView)findViewById(R.id.label)).setText("clicked on XYZ button");
        }
    });

The problem is not in accessing the View of included layout, but in the fact that you cannot achieve this layouts "overlapping". Let me explain: if you add some more views below the button in your a.xml and then try to place some view in your b.xml just below the button then it would make the views from b.xml overlap views from a.xml, however this has not been implemented in Android (yet?). So, the only thing you can do is to put android:layout_below="@id/a_layout" as @Hoàng Toản suggested.

P.S. You may observe same behavior with this a + b layouts combination:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <Button
            android:id="@+id/xyz"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="XYZ" />
    </RelativeLayout>

    <TextView
        android:id="@+id/label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/xyz"
        android:text="Show me below xyz" />
</RelativeLayout>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!