ViewStub
2019-01-03 本文已影响26人
南娇
1.ViewStub时一个大小为0,默认不可见的控件,只有给他设置成view.setVisible或者调用它的inflate方法才会填充布局资源,这样占用的资源比较少
2.应用
<RelativeLayout 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"
tools:context=".MainActivity">
<Button
android:id="@+id/show_bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示"/>
<Button
android:id="@+id/hide_bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="隐藏"
android:layout_alignParentRight="true"/>
<ViewStub
android:id="@+id/viewStub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
//这个Id时自己起的,通过这个id获取引入布局的view
android:inflatedId="@+id/viewstub_layout"
//引入的布局xml
android:layout="@layout/stub_view"/>
</RelativeLayout>
MainActivity
public class MainActivity extends AppCompatActivity{
private Button show_bt,hide_bt;
private ViewStub viewStub;
private View viewstub_layout;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show_bt=findViewById(R.id.show_bt);
hide_bt=findViewById(R.id.hide_bt);
viewStub=findViewById(R.id.viewStub);
show_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
viewstub_layout=viewStub.inflate();
TextView viewstub_text=viewstub_layout.findViewById(R.id.viewStub_text);
viewstub_text.setText("显示了");
}catch (Exception e){
viewStub.setVisibility(View.VISIBLE);
}
}
});
hide_bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewStub.setVisibility(View.GONE);
}
});
}
}
viewStub调用两次inflate()会报错
QQ截图20190103154621.png
inflate()方法源码
public View inflate() {
final ViewParent viewParent = getParent();
if (viewParent != null && viewParent instanceof ViewGroup) {
if (mLayoutResource != 0) {
final ViewGroup parent = (ViewGroup) viewParent;
final View view = inflateViewNoAdd(parent);
replaceSelfWithView(view, parent);
mInflatedViewRef = new WeakReference<>(view);
if (mInflateListener != null) {
mInflateListener.onInflate(this, view);
}
return view;
} else {
throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
}
} else {
throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
}
}
因为获取不到viewParent 所以报错,所以最好时try...catch,但是可以通过setVisibility方法来控制显示与隐藏