Android中ViewStub组件使用

时间:2023-03-08 19:05:49
Android中ViewStub组件使用

1. 概述:

ViewStub组件和<include>标签的作用类似,主要是为了提高布局的重用性,及布局的模块化。它们之间最大的差别是,ViewStub中的布局不会随着它所在布局的渲染而渲染,而<include>标签中的布局会随着它所在布局的渲染而渲染,ViewStub中的布局只有在你需要的时候才会渲染到主界面中。

2. 效果图:

(1)在ButtonOne与ButtonTwo之间存在一个ViewStub布局,如下图:

Android中ViewStub组件使用

(2)单击ButtonOne后渲染ViewStub中的布局,如下图:

Android中ViewStub组件使用

3. 实现代码:

(1)res/layout/main.xml实现:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
  3. android:orientation = "vertical"
  4. android:layout_width = "fill_parent"
  5. android:layout_height = "fill_parent"
  6. >
  7. <Button
  8. android:id = "@+id/show"
  9. android:text = "ButtonOne"
  10. android:layout_width = "wrap_content"
  11. android:layout_height = "wrap_content"
  12. />
  13. <ViewStub
  14. android:id = "@+id/viewStub"
  15. android:layout = "@layout/green_layout"
  16. android:layout_width = "300dip"
  17. android:layout_height = "300dip"
  18. />
  19. <Button
  20. android:layout_width = "wrap_content"
  21. android:layout_height = "wrap_content"
  22. android:text = "ButtonTwo"
  23. />
  24. </LinearLayout>

(2)main.xml中ViewStub组件里的布局实现:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout
  3. xmlns:android = "http://schemas.android.com/apk/res/android"
  4. android:layout_width = "match_parent"
  5. android:layout_height = "match_parent"
  6. android:background = "@color/green">
  7. </LinearLayout>

(4)主Activity实现:

  1. package com.focus.fishme;
  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.view.View;
  5. import android.view.ViewStub;
  6. import android.view.View.OnClickListener;
  7. import android.widget.Button;
  8. public class ViewStubActivity extends Activity {
  9. private ViewStub mViewStub;
  10. private Button mShow;
  11. @Override
  12. public void onCreate(Bundle savedInstanceState) {
  13. super.onCreate(savedInstanceState);
  14. setContentView(R.layout.main);
  15. mViewStub = (ViewStub) findViewById(R.id.viewStub);
  16. mShow = (Button) findViewById(R.id.show);
  17. mShow.setOnClickListener(new OnClickListener() {
  18. public void onClick(View view) {
  19. if (mViewStub != null) {
  20. mViewStub.inflate();
  21. }
  22. }
  23. });
  24. }
  25. }

转自:http://blog.csdn.net/mayingcai1987/article/details/6238609