欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android?ViewStub使用方法學(xué)習(xí)

 更新時間:2022年11月13日 09:47:50   作者:Coolbreeze  
這篇文章主要為大家介紹了Android?ViewStub使用方法學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

前言

當(dāng)渲染一個活動時,這個活動的布局可能會有很多visible為invisible和gone的情況,雖然這些控件雖然現(xiàn)在不顯示在屏幕上,但是系統(tǒng)在加載這個布局文件時還是會加載它的,這就影響了這個頁面的加載效率,因為這些不可見的控件提前加載它們并沒有什么實際的意義,反而會減緩頁面的加載時間,所以為了解決這個問題可以使用ViewStub來懶加載暫時不顯示的布局.

1.ViewStub的優(yōu)勢

簡單來說, ViewStub可以做到按需加載一個布局,我們可以控制它加載的時機,而不是在Activity的onCreate方法中去加載.即懶加載

2.ViewStub的使用

    <ViewStub
        android:id="@+id/stub"
        android:inflatedId="@+id/text"
        android:layout="@layout/text_view_stub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/textView3"
        android:layout_marginTop="180dp"
        android:layout_marginLeft="100dp"/>

屬性 功能

android:inflatedId="@+id/text" 為我們要加載的布局提供一個id android:layout 我們需要加載的布局 除此之外

        app:layout_constraintTop_toBottomOf="@id/textView3"
        android:layout_marginTop="180dp"
        android:layout_marginLeft="100dp"/>

這些代表我們懶加載的布局在父布局的位置,如果懶加載的布局有相同的屬性,將會被覆蓋

//通過id得到viewStub對象
ViewStub viewStub = findViewById(R.id.stub);
//動態(tài)加載布局
 viewStub.inflate();

簡單實戰(zhàn)

1.viewstub就是動態(tài)加載試圖

也就是在我們的app啟動繪制頁面的時候,他不會繪制到view樹中;當(dāng)在代碼中執(zhí)行inflate操作后,她才會被添加到試圖中。其實ViewStub就是一個寬高都為0的一個View,它默認(rèn)是不可見的,只有通過調(diào)用setVisibility函數(shù)或者Inflate函數(shù)才 會將其要裝載的目標(biāo)布局給加載出來,從而達到延遲加載的效果,這個要被加載的布局通過android:layout屬性來設(shè)置。最終目的是把app加載頁面的速度提高了,使用戶體驗更好。

2.看一個簡單的demo

viewstub.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/inflatedStart"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/hello_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:text="DATA EMPTY!"/>
</android.support.constraint.ConstraintLayout>

activity_myviewstub.xml

<?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">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="inflate"
        android:text="inflate" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="setData"
        android:text="setdata"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="hide"
        android:text="hide"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="show"
        android:text="show"/>
    <ViewStub
        android:id="@+id/vs"
        android:inflatedId="@+id/inflatedStart"
        android:layout="@layout/viewstub"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

MyViewStubActivity.java

package com.ysl.myandroidbase.viewstub;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewStub;
import android.widget.TextView;
import com.ysl.myandroidbase.R;
public class MyViewStubActivity extends AppCompatActivity {
    private ViewStub viewStub;
    private TextView textView;
    private View inflate;
    private ConstraintLayout constraintLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myviewstub);
        viewStub = findViewById(R.id.vs);
        //textView  = (TextView) findViewById(R.id.hello_tv);空指針,因為viewstub沒有inflate
    }
    public  void inflate(View view){
        if (inflate == null) {//inflate只會進行一次,當(dāng)?shù)诙握{(diào)用的時候,就會拋異常;也可以try catch進行處理
            inflate = viewStub.inflate();
            constraintLayout = findViewById(R.id.inflatedStart);
            System.out.println(constraintLayout);
            System.out.println("viewStub-------->"+viewStub);
            textView  = viewStub.findViewById(R.id.hello_tv);//獲取到的textview是空的;
            System.out.println("viewStub textView-------->"+textView);//null
            textView  = constraintLayout.findViewById(R.id.hello_tv);
            System.out.println("constraintLayout textView-------->"+textView);
            textView  = findViewById(R.id.hello_tv);
            System.out.println("textView-------->"+textView);
        }
    }
    public void setData(View view){
        if (constraintLayout != null) {
            textView = constraintLayout.findViewById(R.id.hello_tv);
            textView.setText("HAVE DATA !!!");
        }
    }
    public void hide(View view){
        viewStub.setVisibility(View.GONE);
//        if (constraintLayout != null){
//            constraintLayout.setVisibility(View.GONE);
//        }
    }
    public void show(View view){
        viewStub.setVisibility(View.VISIBLE);
//        if (constraintLayout != null){
//            constraintLayout.setVisibility(View.VISIBLE);
//        }
    }
}

3.當(dāng)調(diào)用第二次inflate的時候,會報錯:

編輯切換為居中

添加圖片注釋,不超過 140 字(可選)

我們看一下這是為什么?進入viewStub.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");
        }
    }

可以看到當(dāng)viewParent為空或者不是viewgroup時才會報這個錯誤;那么第一次調(diào)用的時候,肯定是進去了;發(fā)現(xiàn)一個方法replaceSelfWithView(view,parent);view就是我們在布局文件中給viewstub指定的layout所引用的那個布局;parent就是getParent方法得到的,也就是acticity的填充布局LinearLayout;

進去看一下:

private void replaceSelfWithView(View view, ViewGroup parent) {
        final int index = parent.indexOfChild(this);
        parent.removeViewInLayout(this);
        final ViewGroup.LayoutParams layoutParams = getLayoutParams();
        if (layoutParams != null) {
            parent.addView(view, index, layoutParams);
        } else {
            parent.addView(view, index);
        }
    }

可以發(fā)現(xiàn)parent.removeViewInLayout(this);把this就是viewstub從父布局linearlayout中移除了;parent.addView()就是把view(也就是我們引用的布局)添加到了父布局LinearLayout中。

我們用layout inspector來查看一下:

inflate前:可以看到viewstub是灰色的

編輯

添加圖片注釋,不超過 140 字(可選)

inflate后:可以看到viewstub直接被移除了,把引用布局直接放到view樹里了。

編輯

添加圖片注釋,不超過 140 字(可選)

所以當(dāng)我們第二次再調(diào)用inflate方法時,viewstub的parent已經(jīng)為空了;就會拋出此異常;

當(dāng)調(diào)用textView = viewStub.findViewById(R.id.hello_tv);//獲取到的textview是空的;

而使用textView = findViewById(R.id.hello_tv);就可以直接拿到控件對象了;

當(dāng)實現(xiàn)引用布局的顯示和隱藏時,測試發(fā)現(xiàn)使用viewstub的setVisibility()方法可以實現(xiàn),這是為什么呢?;按理說使用constraintLayout.setVisibility()當(dāng)然也可以;根據(jù)上面的view樹結(jié)構(gòu)來看,好像使用引用布局的setVisibility()方法更合理一些;

下面我們再來看看viewstub的setVisibility()為什么也可以;跟進源碼看看:

編輯切換為居中

添加圖片注釋,不超過 140 字(可選)

源碼中使用mInflatedViewRef獲取到view,然后設(shè)置隱藏與顯示;mInflatedViewRef是一個view的弱引用WeakReference

其實在上面的inflate方法中已經(jīng)為其添加了mInflatedViewRef = new WeakReference<>(view);這個view就是viewstub中的引用布局;

所以,使用viewstub可以實現(xiàn)相同的顯示或隱藏效果;

從上圖的最后一個紅色框中可以發(fā)現(xiàn),假設(shè)現(xiàn)在我沒有調(diào)用inflate方法,而是直接點擊了show按鈕;然后引用布局也可以繪制出來;這就是我在寫demo的時候,直接上去點擊show按鈕,竟然也可以顯示的原因。

編輯切換為居中

添加圖片注釋,不超過 140 字(可選)

以上就是Android ViewStub的使用與簡單的演練;如果想要進階自己Android技能,可以參考這份《Android核心技術(shù)筆記》里面記錄有Android的核心技術(shù)與其他前沿技術(shù)。

文末

Android ViewStub的使用注意事項

inflate方法只能調(diào)用一次,再次調(diào)用會出異常 我們看下inflate方法的源碼,一旦第二次調(diào)用inflate方法,我們的到viewParent將等于null,會報 throw new IllegalStateException(“ViewStub must have a non-null ViewGroup viewParent”);異常,所以總之一句話,這個懶加載只能加載一次

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");
       }
   }

以上就是Android ViewStub使用方法學(xué)習(xí)的詳細(xì)內(nèi)容,更多關(guān)于Android ViewStub使用的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論