android-布局优化:merge+include

来源:互联网 发布:免费群发短信软件 编辑:程序博客网 时间:2024/05/17 03:49

介绍:

1.merge布局 和FrameLayout类似,相同的效果.不同的是 merge布局只能被<include>标签包含. 或者Activity.setContentView所使用.当LayoutInflater遇到能被其他layout用<include>包含进去,并不再另外生成ViewGroup容器,本元素也特别有用这个标签时,它会跳过它,并将<merge />内的元素添加到<merge />的父元素里. Activity能直接使用的原因是Activity的父元素是FrameLayout2 merge 能被其他layout用<include>包含进去,并不再另外生成ViewGroup容器.就是说,会减少一层layout到达优化layout的目的
merge主要是进行UI布局的优化的,删除多余的层级,优化UI。<merge/>多用于替换frameLayout或者当一个布局包含另一个布局的时候,<merge/>标签用于消除师徒层次结构中多余的视图组。例如你的朱布局文件是垂直的,此时如果你引入一个垂直布局的<include>.这时如果include布局使用的LinearLayout就没意义了,使用的话反而减慢你的UI表现。这时可以使用<merge/>标签优化。<merge>标签也就是排除一个布局插入另一个布局产生的多余的viewgroup.
<merge />标签有什么限制没?<merge />只能作为XML布局的根标签使用。当Inflate以<merge />开头的布局文件时,必须指定一个父ViewGroup,并且必须设定attachToRoot为true

示例一:

<merge 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" >    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="我是button3" />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="我是button2" /></merge>

这里注意是frameLayout的效果,为什么用在这里呢,因为android有一个默认的FrameLayout的布局

上面布局的效果图:

示例二:

activity_maini.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/container"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <include layout="@layout/fragment_main" /></LinearLayout>

fragment_main.xml

<merge 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">    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="我是button3" />    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="我是button2" /></merge>

MergeActivity.java

package com.example.administrator.myapplication;import android.os.Bundle;import android.support.annotation.Nullable;import android.support.v7.app.AppCompatActivity;/** * Created by Administrator on 2017/6/1. */public class MergeActivity extends AppCompatActivity {    @Override    protected void onCreate(@Nullable Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_maini);    }}

效果图:

参考:

android布局优化-merge

android布局文件 merge 标签的使用

阅读全文
0 0
原创粉丝点击