簡單示例java
main.xmlandroid
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- 靜態的加載佈局文件 --> <include android:layout_width="wrap_content" android:layout_height="wrap_content" layout="@layout/next" > </include> <!-- 動態的加載佈局文件 --> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#FFCCDD" > <ViewStub android:id="@+id/stub" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout="@layout/next" > </ViewStub> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="動態添加布局" > </Button> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="動態隱藏佈局" > </Button> </LinearLayout> </LinearLayout>
next.xmlapp
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <RatingBar android:id="@+id/ratingBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
main.javaide
package com.leaf.android; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewStub; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RatingBar; public class Main extends Activity { private Button button1, button2; private ViewStub viewStub; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); button1 = (Button) this.findViewById(R.id.button1); button2 = (Button) this.findViewById(R.id.button2); viewStub = (ViewStub) this.findViewById(R.id.stub); button1.setOnClickListener(new OnClickListener() { public void onClick(View v) { // 表示填充動態佈局 View view = viewStub.inflate(); LinearLayout layout = (LinearLayout) view; RatingBar bar = (RatingBar) layout .findViewById(R.id.ratingBar1); bar.setNumStars(3); } }); button2.setOnClickListener(new OnClickListener() { public void onClick(View v) { viewStub.setVisibility(View.GONE);// 隱藏佈局 } }); } }
效果:佈局