Android布局优化

 1、merge 标签

             merge标签的作用是实现布局文件的重用。就是说,为了高效复用及整合布局,使布局轻便化,我们可以使用merge标签将一个布局嵌入到另一个布局中,或者说将多个布局中的相同元素抽取出来,独立管理,再复用到各个布局中,便于统一的调整。 

使用方法及注意事项:

   (1)<merge />只可以作为xml layout的根节点。

   (2)当需要扩充的xml layout本身是由merge作为根节点的话,需要将被导入的xml layout置于 viewGroup中,同时需要设置attachToRoot为True。

下面是一个简单的例子,通过Android Hierarchy View 分析布局结构 :   

   (1)不使用merge标签

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.admin.layoutdemo.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</FrameLayout>

 

 (2)使用merge标签

<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.admin.layoutdemo.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

</merge>

 

   可以分析出如果使用merge标签,可以优化根节点。因为setContentView底层就是Fragment。所以当独立的一个布局文件最外层是FrameLayout的时候,并且和这个布局不需要设置 background 或者 padding的时候,可以使用<merge>标签来代替FrameLayout布局。

 2、include

include 与 merge 作用都是为了高效复用及整合布局,使布局轻便化

     关键代码: <include layout="@layout/layout_toolbar2"/>

          具体操作和普通控件一样

 3、ViewStub

ViewStub 是一个轻量级的View,没有尺寸,不绘制任何东西,因此绘制或者移除时更省时。(ViewStub不可见,大小为0),实现View的延迟加载,避免资源的浪费,在需要的时候加载View(懒加载)。

            使用方法:

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.admin.layoutdemo.MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="视图ViewStub测试"/>
    <ViewStub
        android:id="@+id/viewStub"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inflatedId="@+id/ceshi"
        android:layout="@layout/layout_stub"/>

</LinearLayout>

   

 

inflatedId 指定了懒加载视图跟节点的ID。android:layout指定了懒加载的视图,他在加载前显示在视图中,加载后(inflate,setVisable)变为要加载的节点,他自己被销毁,就是这么无私..,注意事项,首先销毁后(inflate),不能被调用,其此懒加载的布局里面不能含有merge标签

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值