布局优化include, viewstub, merge

布局优化
1.include

视图引入,可以配合merge使用
重用布局

2.merge

减少视图层级
步骤如下:
1、创建merge视图

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

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="123" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="123" />
</merge>

2、视图引入

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context="com.example.ticker.myapplication.MainActivity">
    <include layout="@layout/merge_layout"></include>
</LinearLayout>
3.ViewStub

引入一个外部布局,不同的是,viewstub引入的布局默认不会扩张,即既不会占用显示也不会占用位置,从而在解析layout时节省cpu和内存。ViewStub是一个不可见的,大小为0的视图,可以在运行过程中延时加载布局资源,inflate 方法只能被调用一次,因为调用后viewStub对象就被移除了视图树;
使用步骤如下:
1、创建需要加载的布局

 <?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">
    <Button
        android:layout_width="match_parent"
        android:text="button01"
        android:layout_height="wrap_content" />
    <Button
        android:layout_width="match_parent"
        android:text="button02"
        android:layout_height="wrap_content" />
</LinearLayout>

2、在需要引入的xml中引入

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ticker.myapplication.MainActivity">
    <ViewStub
        android:id="@+id/viewstub"
        android:layout_width="match_parent"
        android:layout="@layout/viewstub_layout"
        android:layout_height="match_parent" />
</RelativeLayout>

3、使用

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewStub viewStub = (ViewStub) findViewById(R.id.viewstub);
        View view = viewStub.inflate();
    }
}

Android抽象布局——include、merge 、ViewStub
ViewStub--使用介绍

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容