ViewStub是一种可需性的控件,同时继承自ViewGroup,我们可以在需要的时候进行UI显示,好比View的Gone与Visibility,而且ViewStub只是加载一次控件,之后当前的ViewStub会重置为null,如果需要进行重用,可以进行条件判断,如果不进行判断,则会报java.lang.IllegalStateException错误。
UI:
注意: 1.ViewStub配置layout的属性,进行itemlayout填充 2.在代码代码中获得ViewStub之后,直接inflate()就好 3.为了防止在此点击崩溃,我直接设置不可点击按键
MainActivity :
package com.example.viewstub; import android.R.bool; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewStub; import android.widget.TextView; public class MainActivity extends Activity { private ViewStub mStub; private TextView mTv; public boolean is; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } private void initView() { mTv = (TextView) findViewById(R.id.text); mStub = (ViewStub) findViewById(R.id.stub); mTv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mStub.inflate(); mTv.setEnabled(false); } }); } }MainActivity Xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:id="@+id/text" android:text="点击之后,按需求显示ViewStub在下面UI" /> <ViewStub android:id="@+id/stub" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:layout="@layout/view_stub" /> </LinearLayout>填充的layout,View_Stub:
<?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" > <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="This textview is View—Stub" /> </LinearLayout>最终效果: