在运行时更改包含布局的组件

时间:2013-10-18 11:20:14

标签: android xml android-layout background include

我有common_views.xml,我定义了所有其他布局共有的视图,并将这个common_views.xml包含在这些其他布局中。

common_views.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="fill_parent" android:id="@+id/water_room_common"
    android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageButton android:id="@+id/bag" android:layout_width="65dp"
        android:layout_height="65dp" android:layout_alignBottom="@+id/storage"
        android:layout_alignParentRight="true" android:layout_marginRight="10dp"
        android:adjustViewBounds="true"  />
    <RelativeLayout...> ... </RelativeLayout>
   ...
</RelativeLayout>

以下是其中一个包含common_views.xml的布局,我称之为water_room_wall1.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/wall1Layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/wall1withkey"
    tools:context=".FireRoomActivity" >

<include layout="@layout/common_views" android:id="@+id/common_views" />

....
</RelativeLayout>

在我的活动中,我想以编程方式更改common_views.xml中imagebutton @ id / bag的背景:

 public class MainActivity extends Activity {
    RelativeLayout parentLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.water_room_wall1);
            parentLayout = (RelativeLayout)findViewById(R.id.wall1Layout);
    }

    ...
ImageButton newItem  =(ImageButton)parentLayout.findViewById(R.id.common_views).findViewById(R.id.bag);
newItem.setBackgroundResource(R.drawable.key_stored);

}

但这会丢弃water_room_wall1.xml布局的所有其他组件(它们消失),只显示带有更改的图像按钮的common_views.xml布局。这是为什么?是否有任何方法只更改包含布局的组件而不影响父布局?

0 个答案:

没有答案
相关问题