ViewStub
ViewStub
布局惰性加載機(jī)制,它是不可見的占據(jù)窗口大小為0的一個(gè)View,在運(yùn)行時(shí)加載布局資源,當(dāng)其visible或者調(diào)用inflate()方法時(shí),就會(huì)變?yōu)榭梢?#xff0c;并將其本身加載出來的布局傳遞給父布局,但是他只能被加載一次,重復(fù)加載會(huì)報(bào)這個(gè)錯(cuò)誤 Caused by: java.lang.IllegalStateException: ViewStub must have a non-null ViewGroup viewParent。因?yàn)樗虞d完本身就不存在了,自然不能調(diào)用。
通常一個(gè)布局里面對(duì)應(yīng)不同狀態(tài)有好幾個(gè)布局的時(shí)候,會(huì)寫到一起,設(shè)置他們的Visibility屬性為gone或者invisible,在代碼中進(jìn)行邏輯控制展現(xiàn),比較麻煩,而且這樣寫雖然看不到,但扔被實(shí)例化,消耗資源,而ViewStub則進(jìn)行了性能優(yōu)化。
使用
首先我們?cè)诓季种卸x一個(gè)ViewStub,里面有一個(gè)layout屬性,就是我們要惰性加載的布局,在這里已經(jīng)定義好了,只是默認(rèn)不可見,不占據(jù)空間
<?xml version="1.0" encoding="utf-8"?> <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"tools:context=".MainActivity"><ViewStubandroid:id="@+id/stub"android:layout="@layout/subtree"android:layout_width="120dip"android:layout_height="40dip" /></LinearLayout>接下來在主活動(dòng)中進(jìn)行處理
public class MainActivity extends AppCompatActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ViewStub viewStub=findViewById(R.id.stub);//viewStub.setVisibility(View.VISIBLE);View inflated=viewStub.inflate();//與上一個(gè)寫法一樣效果(設(shè)置其可見與用inflate()加載一樣)//viewStub.inflate();寫第二遍會(huì)報(bào)錯(cuò),只能加載一次TextView hintText=inflated.findViewById(R.id.text);hintText.setText("qwerty");} }直接調(diào)用 viewStub.inflate()也可以,只不過用View接一下,可以繼續(xù)處理布局里面的控件。
參考: https://www.jianshu.com/p/175096cd89ac
https://blog.csdn.net/cx1229/article/details/53505903
總結(jié)
- 上一篇: Codeforces Round #29
- 下一篇: PB获取系统用户名