Android ViewStub基本使用
1.介绍
ViewStub在Android中可以看为占位符,可以动态控制界面的显示。
2.使用样例
主界面Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ViewStub
android:id="@+id/myviewstub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout="@layout/viewstablayout"/>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<Button
android:id="@+id/open_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show"
/>
<Button
android:id="@+id/close_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hide"
/>
</LinearLayout>
</LinearLayout>
ViewStub界面Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="品牌:卡马 KEPMA"/>
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="型号:D1C"/>
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="规格:41寸"/>
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="面板:云杉木"/>
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="底侧:南洋木"/>
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="弦钮:镀黑镍打钢印全封闭弦钮"/>
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="包边:珍珠条镶嵌"/>
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="品味:21品"/>
</LinearLayout>
Activity调用:
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.open_button:
if (!isInit) {
View view = mViewStub.inflate();
LinearLayout linearLayout = (LinearLayout) view;
isInit = true;
} else {
mViewStub.setVisibility(View.VISIBLE);
}
break;
case R.id.close_button:
mViewStub.setVisibility(View.GONE);
break;
default:
break;
}
}
3.注意点
ViewStub在使用中只能inflate一次,之后通过setVisibity方法进行显示或隐藏。