28

我将第二个布局包含在第一个布局中,如下所示:

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:layout_gravity="clip_horizontal"
    android:layout_alignParentLeft="true" 
    android:id="@+id/rlMenu"
    >

    <Button
        android:id="@+id/bMusteriler"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Musteriler"
        android:textSize="45dp"
        android:layout_alignParentLeft="true"
         />

</RelativeLayout>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_toRightOf="@id/rlEkranlar"
     >

    <include
        android:id="@+id/include1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        layout="@layout/ikinci" />

</RelativeLayout>
</RelativeLayout>

问题是如何在单击按钮时更改包含的布局(在 java 代码上)?

4

3 回答 3

60

我建议ViewFlipperRelativeLayout你的include陈述中。试试这样:

<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/vf"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <include android:id="@+id/include1" layout="@layout/ikinci" />
    <include android:id="@+id/map" layout="@layout/third_layout" />

</ViewFlipper>

如下访问 ViewFlipper。最初输出第一个布局:

ViewFlipper vf = (ViewFlipper)findViewById(R.id.vf);

对于按钮 onClickListener:

button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                vf.setDisplayedChild(1);
            }
        });
于 2011-12-23T04:48:25.287 回答
24

有两种方法可以更改代码中的布局:

A. 改变可见性。在您的 xml 中包含两种不同的布局:

<include 
    android:id="@+id/id1"
    android:visibility="visible"/>
<include 
    android:id="@+id/id2"
    android:visibility="gone"/>

在代码中使用这个:

findViewById(R.id.id1).setVisibility(View.GONE);
findViewById(R.id.id2).setVisibility(View.VISIBLE);

B. 手动添加孩子。使用与现在相同的 xml 并添加可以添加或删除子项的代码:

yourRelativeLayout.removeAllViews();
yourRelativeLayout.addView(viewToInclude);

题外话:

您不需要xmlns:android在 RelativeLayout 中编写参数。仅用于布局文件中最顶部的标签。

于 2011-12-23T04:45:16.063 回答
0

您是否尝试过获取包含其他 xml 并使用的 xml 的当前视图的实例findViewById()。视图 v 是第一个布局,您使用此视图.findViewById()

于 2011-12-21T12:49:24.373 回答