歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android中使用ViewStub來提高UI的加載的性能

Android中使用ViewStub來提高UI的加載的性能

日期:2017/3/1 10:39:57   编辑:Linux編程
首先看下API中的ViewStub

根據的文檔的說明,ViewStub是一種默認不可見的試圖,它沒有大小,所以不能被改變,也不能通過某些把viewstub添加到布局當中來,

不過我們可以使用inflate()來吧ViewStub中的試圖增加進行,這樣可以實現動態的添加試圖,不必要每次在onCreate()的時候就加載布局,可以提高我們的性能。

Demo中的使用方法:

1:新建布局文件 設置<ViewStub>節點

2: 在Activity中進行按鈕點擊 viewStub = (ViewStub) findViewById(R.id.mystub);

3: View view = viewStub.inflate(); 把ViewStub中的View增添進來

下面Demo源代碼:

主Activity類:

[java]
  1. package com.jiangqq.viewstubdemo;
  2. import Android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.View;
  5. import android.view.View.OnClickListener;
  6. import android.view.ViewStub;
  7. import android.widget.Button;
  8. public class ViewStubActivity extends Activity {
  9. private Button btn;
  10. private ViewStub viewStub;
  11. @Override
  12. public void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.main);
  15. btn = (Button) findViewById(R.id.btn);
  16. btn.setOnClickListener(new OnClickListener() {
  17. @Override
  18. public void onClick(View v) {
  19. viewStub = (ViewStub) findViewById(R.id.mystub);
  20. View view = viewStub.inflate();
  21. v.setEnabled(false);
  22. }
  23. });
  24. }
  25. }

布局文件:

main.xml:

[html]
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. android:orientation="vertical" >
  6. <Button
  7. android:id="@+id/btn"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:text="點擊確定" />
  11. <ViewStub
  12. android:id="@+id/mystub"
  13. android:layout_width="wrap_content"
  14. android:layout_height="wrap_content"
  15. android:layout="@layout/demo_viewstub" >
  16. </ViewStub>
  17. </LinearLayout>
demo_viewstub.xml:
[html]
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:id="@+id/layout"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:orientation="vertical" >
  7. <TextView
  8. android:id="@+id/tv"
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="ViewStubDemo_Byjiangqq" />
  12. </LinearLayout>
效果截圖:

Copyright © Linux教程網 All Rights Reserved