Android开发Android开发经验谈Android技术知识

Android优化篇 ViewStub按需加载布局

2019-01-26  本文已影响5人  TryEnough

原文链接

更多教程


你将学到

1.ViewStub标签的使用姿势
2.ViewStub标签的使用例子
3.ViewStub标签的使用注意点

ViewStub标签的使用姿势

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="#36e7ea"
        android:gravity="center"
        android:textSize="18sp" />
        
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

    <Button            //点击按钮时才加载下面的ViewStub布局
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="加载ViewStub" />

    <ViewStub  //这个布局现在还不会被添加到布局树中
        android:id="@+id/view_stub"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout="@layout/test" />  //这里指定要加载的布局名字
        
</LinearLayout>
Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            View view = ((ViewStub)findViewById(R.id.view_stub)).inflate();  //加载出来用view接收
            TextView tv = (TextView) view.findViewById(R.id.text_view); //然后可以用view访问它的子控件
            tv.setText("ViewStub的使用");
    }
});

效果:
点击按钮前:



点击按钮后,出现了需要临时加载的布局:


ViewStub使用注意点

原文链接

更多教程

上一篇 下一篇

猜你喜欢

热点阅读