在我的情况下按下按钮时如何更新内容? (类似标签的功能)

时间:2011-07-12 13:37:24

标签: android android-layout android-emulator android-widget android-manifest

我的 main.xml 布局只包含两个按钮和一个内容区域,如下所示:

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


    <LinearLayout 
        android:id="@+id/myBtns"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
    >
        <Button
            android:id="@+id/btn_one"
            android:layout_width="100dip"
            android:layout_height="30dip"
                android:text="button one"
         />
         <Button
            android:id="@+id/btn_two"
            android:layout_width="100dip"
            android:layout_height="30dip"
                android:text="button two"
         />
    </LinearLayout>

    <LinearLayout 
        android:id="@+id/content_area"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    >
         <!--different button press will embed different content here-->

    </LinearLayout>


   </LinearLayout>

我想创建自己的标签式功能,每按一次按钮都会更新按钮下方的内容(content_area)。所以我准备了另外两个内容布局:

content_one.xml

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

    <TextView.../>
    <Button .../>

</LinearLayout>

content_two.xml

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

    <Gallery.../>
    <Button .../>

</LinearLayout>

通过上面显示的所有简单代码,我想实现以下功能:

main.xml

  • 按下button_one时, content_one.xml 将嵌入 main.xml content_area;

  • 按下button_two后, main.xml content_area将更新为 content_two.xml

这意味着使用按钮创建标签式功能

我的问题是如何使用外部布局xml文件更新content_area(例如 content_one.xml &amp; content_two.xml )已嵌入{{1}内我的 main.xml 布局?

这是:

content_area

---------------- UPDATE --------------------------- -

我试过了:

button_one.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v){
        //What to do here?? to update the content_area in main.xml with an external xml layout
    }
});

但它不起作用,为什么?

1 个答案:

答案 0 :(得分:0)

您可以使用LayoutInflater从xml文件创建视图层次结构。以下代码返回我的xml视图。

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View inflatedView = inflater.inflate(R.layout.content_one, null);

要膨胀的第一个参数(...)是要膨胀的xml文件。第二个参数是膨胀视图的可选父级。就我而言,我没有。然后,您可以将视图添加到您的内容区域。

contentArea.addView(inflatedView);
相关问题