• ViewStub的简单用法和说明


    最近无意间知道了ViewStub,所以特地的去了解了一下

    都知道ViewStub是一个不可见的,大小为0的View,实际上跟include差不多,但是ViewStub要更加节约资源。被称为是“懒惰的include”,因为ViewStub只会在你需要用到的时候加载,下面就看一下用法

    这里有两个布局,这个是主布局activity_main.xml

    <RelativeLayout 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="com.ehsure.lesson_one.MainActivity">
    <ViewStub
    android:id="@+id/main_vs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout="@layout/item_one"
    />
    </RelativeLayout>

    这个是子布局item_one.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
    android:id="@+id/item_one_tv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/str_one"
    />

    <Button
    android:id="@+id/item_one_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btn_one"
    android:onClick="show"
    />

    </LinearLayout>

    这个是 Activity里面的代码:

    public class MainActivity extends Activity {
    private ViewStub viewStub;
    private View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //显示ViewStub的内容
    viewStub = (ViewStub) findViewById(R.id.main_vs);
    view = viewStub.inflate();
    // viewStub.setVisibility(View.VISIBLE);

    //对ViewStub包含布局的控件进行操作
    TextView textView = (TextView)view.findViewById(R.id.item_one_tv);
    textView.setText("hahahaha");

         
        //你也可以通过延迟来显示或者更改你的ViewStub包含布局的内容
        new Timer().schedule(new TimerTask() {
         @Override
         public void run() {
        handler.sendEmptyMessage(1);
         }
        },2000);
        }

    Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
    super.handleMessage(msg);
    if(msg.what==1){
    TextView textView = (TextView)view.findViewById(R.id.item_one_tv);
    textView.setText("哈哈哈");
    Button button = (Button)view.findViewById(R.id.item_one_btn);
    button.setText("DIANJI");
    }
    }
    };


    }

    其中让ViewStub可见有两种方法: 第一是通过setVisibility,第二种就是通过inflate()方法,但是这两句代码不能共存,因为inflate方法只能调用一次,而setVisibility实际上会间接调用inflate.

    其次ViewStub有一个限制就是不能使用merge标签,说到这里我顺便说一下merge标签

    merge最常见的用处就是替换掉FrameLayout布局,官方的说法是这样可以减少一级布局层次,达到布局优化的效果

  • 相关阅读:
    分治法(待整理)
    NP完全问题
    合并排序
    插入排序
    算法基础知识(算法导论)
    分支定界法
    RUCM简介
    大一编程基础培训]==06课==Python的字符串和编码
    python加密包利用pycrypto包进行AES、DES、MD5等加密
    pyecharts模块
  • 原文地址:https://www.cnblogs.com/carrie124/p/carriefeng.html
Copyright © 2020-2023  润新知