【发布时间】:2011-07-12 13:37:23
【问题描述】:
我的 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
这意味着使用按钮来创建一个类似标签的功能。
我的问题是如何使用嵌入在我的 content_area 中的外部布局 xml 文件(例如 content_one.xml 和 content_two.xml)更新 content_area main.xml 布局?
那是:
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
}
});
----更新--------------- -
我试过了:
button_one.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
LayoutInflater inflater = (LayoutInflater)MyActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View inflatedView = inflater.inflate(R.layout.content_one, null);
LinearLayout contentArea= (LinearLayout) findViewById(R.id.content_area);
contentArea.addView(inflatedView);
}
});
但它不起作用,为什么?
【问题讨论】:
-
这个之前的回答可以帮到你:stackoverflow.com/questions/5961522/…
-
@Fortega ,我试过了,还是不行,看我的更新
标签: android android-layout android-emulator android-widget android-manifest