本帖最后由 liu 于 2018-12-26 14:56 编辑  
 
ViewStub 
 
  
 
 
ViewStub是一个不可见,size 大小为0的一个View ,用于View的延迟加载,在需要的时候才加载View 
 
 
注意:ViewStub只能Inflate一次,ViewStub在加载完后会被移除,多次Inflate会报错 
 
用法: 
 
调用setVisibility(View.VISIBLE)或inflate()来加载layout 
 
activity_main.xml: 
[XML] 纯文本查看 复制代码 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Hello World"
        android:textSize="20sp" />
    <ViewStub
        android:id="@+id/vb"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout="@layout/layout_viewstub" />
</RelativeLayout>
 
layout_viewstub.xml:[XML] 纯文本查看 复制代码 <?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:gravity="center"
    android:orientation="vertical">
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:src="@drawable/fengjing" />
</LinearLayout> MainActivity:[Java] 纯文本查看 复制代码 package com.company.helloworld.firstapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.ViewStub;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewStub viewStub = (ViewStub) findViewById(R.id.vb);
        viewStub.inflate();
    }
}
 
运行结果: 
         
        
 
 
 |