android抽象布局include、merge、ViewStub

android在布局优化中提到三种布局include、marge、ViewStub。

 

1.重用布局<include />


include可以重用布局文件。

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

  1.include可以使用单独的layout文件,这个也是必须的。

  2.可以有多个相同的include标签

 

2.减少UI层级merge


merge标签在UI的结构优化中起着非常重要的作用,它可以删减多余的层级,优化UI。merge多用于替换FrameLayout或者当一个布局包含另一个时,merge标签消除视图层次结构中多余的视图组。例如你的主布局文件是垂直布局,引入了一个垂直布局的include,这是如果include布局使用的LinearLayout就没意义了,使用的话反而减慢你的UI表现。这时可以使用merge标签优化。

<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</merge>

 

3.动态加载ViewStub


ViewStub最大的特点是可以需要时在加载。如各种不常用的布局想进度条、显示错误消息等。

<ViewStub
        android:id="@+id/viewStub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

加载布局可以使用下面俩种方式

((ViewStub) findViewById(R.id.viewStub)).setVisibility(View.VISIBLE);

    View importPanel = ((ViewStub) findViewById(R.id.viewStub)).inflate();

 

posted @ 2018-01-05 09:40  不骄不傲  阅读(149)  评论(0编辑  收藏  举报