ViewStub 简介
在實際開發中,ViewStub 在提升用戶體驗和優化性能方面都是有一定作用的!
ViewStub就是一個寬高都為0的一個View,它默認是不可見的,只有通過調用setVisibility函數或者Inflate函數才會將其要裝載的目標布局給加載出來。也就是頁面默認是不加載ViewStub所指向的View的,而ViewStub本身是一個輕量級的View,占用資源非常小的控件。
這就為我們一開始加載頁面的時候省出來了資源,從而提升性能!
還有在一些頁面我們需要延時加載的內容,我們也可以使用ViewStub,比如我們電商平臺的產品詳情頁面,它底部的相關產品推薦,這個我們剛進入產品詳情頁面完全可以先不加載它,等我們的詳情頁面加載出來了我們在使用ViewStub.inflate(),讓其顯示出來!這樣就能提升我們一開始加載頁面的速度和內存開支!
還有就是我們在一些頁面是需要根據不同的情況顯示和隱藏一些控件,比如還是我們的產品詳情頁面,有些產品是帶有優惠券的,有些則是不帶的,這個時候我們帶有優惠券的就需要把優惠券顯示出來!我們用ViewStub,頁面開始是用不加載優惠券相應的控件的,當有優惠券時我們再去加載,這樣也就節省了很多資源!
我們一個頁面可能看不出來多大的差別,感覺現在手機內存也都大了,不在乎那么一點內存!可是開發中我們明確的知道我們手機上的每個APP分到的實際內存還是很有限的!我們要是每個頁面都能少開支一些,我們的APP性能將提升很多!
而我們的ViewStub 其實很簡單,也是希望大家能夠熟悉它并使用它!
這里需要注意的是ViewStub只能Inflate一次,之后會被置空,所以之后ViewStub是沒有辦法控制它指向的layout的!
下面給大家看一個簡單的例子:
主頁面UI,兩個ViewStub
<?xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center_horizontal"><ViewStubandroid:id="@+id/viewstub_text1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="5dip"android:layout_marginRight="5dip"android:layout_marginTop="10dip"android:layout="@layout/text1_layout"/><ViewStubandroid:id="@+id/viewstub_text2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="5dip"android:layout_marginRight="5dip"android:layout="@layout/text2_layout"/> </LinearLayout>text1_layout 的布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="wrap_content"android:layout_height="wrap_content"><TextViewandroid:id="@+id/text1"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="#ffffff"android:gravity="center"android:text="吃飯"android:textColor="@color/text_color"android:textSize="16sp"/> </LinearLayout>text2_layout 的布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="wrap_content"android:layout_height="wrap_content"><TextViewandroid:id="@+id/text2"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="#ffffff"android:gravity="center"android:text="睡覺"android:textColor="@color/text_color"android:textSize="16sp"/> </LinearLayout>Activity代碼
public class MainActivity extends AppCompatActivity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);String str = getIntent.getStringExtra("type");if (str.equals("吃飯")) {ViewStub stub = (ViewStub) findViewById(R.id.viewstub_text1);stub.inflate();} else {ViewStub stub = (ViewStub) findViewById(R.id.viewstub_text2);stub.inflate();}} }總結
以上是生活随笔為你收集整理的ViewStub 简介的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NLP开源框架
- 下一篇: BotVS开发基础—2.1 账户、行情、