Android Layout 中XML 加载模块的方式总结

在Android开发中,对于在Xml文件中布局块的加载常见的就是include的静态加载ViewStub的动态加载

(1)静态加载


<include layout="@layout/otherLayout"/>
是在布局加载的过程中,同时加载,被加载的模块和其他模块加载的时间一样。

静态加载的基本使用

<LinearLayout 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"
    android:orientation="vertical" >

    <include layout="@layout/B" />

    <Button
        android:id="@+id/showBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button1" />
</LinearLayout>

(2)动态加载

<ViewStub android:layout="@layout/otherLayout"/>

需要被加载的模块初始时没有被加载进内存,当需要使用的时候才会被动态加载进内存。ViewStub 本质上也是一个View  他的继承关系 Object<- View<-ViewStub  ,在性能优化方面是常见的,因为只要不需要就不用加载他,因为像其他布局只要存在,初始化就会加载,虽然设置了Gone 但是他们依然占据着内存。ViewStub加载完以后就会自我移除,ViewStub的子控件会交给父布局来处理,ViewStub只能被加载一次。想要布局加载两次就得需要应用重启。ViewStub不能加载具体的View,需要加载具体的布局文件。

ViewStub的属性和方法

布局文件

<LinearLayout 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"
    android:orientation="vertical" >

    <Button
        android:id="@+id/showBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="button1" />
 <ViewStub
        android:id="@+id/vs"
        android:layout="@layout/viewstub"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

java文件
public class MainActivity extends AppCompatActivity {
    private ViewStub viewStub;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewStub = (ViewStub) findViewById(R.id.vs);
        //textView  = (TextView) findViewById(R.id.hello_tv);// 空指针   ViewStub加载的布局中的控件,因为此时ViewStub还未初始化,所以子控件还是找不到的。
    }
    public  void inflate(View view){
        viewStub.inflate();
        //textView  = (TextView) viewStub.findViewById(R.id.hello_tv);空指针  viewStub已经被移除了
        textView  = (TextView) findViewById(R.id.hello_tv);
    }
    public void setData(View view){
        textView.setText("Hello ");

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值