AndroidでViewStubを使いたいので、助けてください。私が作成しました
ViewStub stub = new ViewStub;
View inflated = stub.inflate();
プログラムで使用する方法は?
ドキュメントが言うように、怠惰に膨張ViewStub
するです。View
ViewStub
次のように XML ファイルでa を宣言できます。
<ViewStub android:id="@+id/stub"
android:inflatedId="@+id/subTree"
android:layout="@layout/mySubTree"
android:layout_width="120dip"
android:layout_height="40dip" />
android:layout
属性は、 の呼び出しの次に膨張する への参照View
ですinflate()
。そう
ViewStub stub = (ViewStub) findViewById(R.id.stub);
View inflated = stub.inflate();
メソッドinflate()
が呼び出されると、がその親から削除され、右側(レイアウトのルート ビュー)ViewStub
に置き換えられます。View
mySubTree
これをプログラム的に実行したい場合、コードは次のようになります。
ViewStub stub = new ViewStub(this);
stub.setLayoutResource(R.layout.mySubTree);
stub.inflate();
単純に ViewStub を使用して、レイアウトのレンダリングの効率を高めます。ViewStub を使用すると、手動でビューを作成できますが、ビュー階層に追加することはできません。実行時に簡単に膨張できます。ViewStub が膨張している間、viewtub のコンテンツは、viewtub で定義されたレイアウトに置き換えられます。
activity_main.xml は、viewtub を定義しましたが、最初に作成しませんでした。
簡単な例で理解が深まり、
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="create the view stub" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hide the stub." />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<ViewStub
android:id="@+id/stub_import"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:inflatedId="@+id/content_import"
android:layout="@layout/splash" />
</RelativeLayout>
</LinearLayout>
実行時にインフレートすると、コンテンツはビュータブで定義されたレイアウトに置き換えられます。
public class MainActivity extends Activity {
Button b1 = null;
Button b2 = null;
ViewStub stub = null;
TextView tx = null;
int counter = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.btn1);
b2 = (Button) findViewById(R.id.btn2);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (stub == null) {
stub = (ViewStub) findViewById(R.id.stub_import);
View inflated = stub.inflate();
tx = (TextView) inflated.findViewById(R.id.text1);
tx.setText("thanks a lot my friend..");
}
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (stub != null) {
stub.setVisibility(View.GONE);
}
}
});
}
ビュー階層をもう一度見てみましょう。
ビュータブを膨張させると、ビュー階層から削除されます。