先推荐两篇大佬的文章:
郭霖的Android布局优化,比较浅显易懂,我也是根据这个写的笔记
然后写写我的总结
(1)可用include实现布局嵌套
方法就是在主页面里面加个include标签:
<include
android:layout_width="368dp"
android:layout_height="wrap_content"
layout="@layout/title_bar"
/>
把想要嵌套的layout嵌套进去即可。
(2)应减少布局嵌套,因为安卓解析布局比较耗时,可用<merge>标签代替布局标签
例:使两个button 被merge进主页面,button布局:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
>
<Button
android:id="@+id/ok"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="OK" />
<Button
android:id="@+id/cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:text="Cancel" />
</merge>
然后在主页面中添加:
<include
layout="@layout/cancel_ok"/>
效果如下:
(3)仅在需要时才加载布局,使用ViewStub。ViewStub虽说也是View的一种,但是它没有大小,没有绘制功能,也不参与布局,资源消耗非常低,将它放置在布局当中基本可以认为是完全不会影响性能的。
先来3个EditText,等会儿ViewStub进主页面
<?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"
android:orientation="vertical" >
<EditText
android:id="@+id/edit_extra1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="Extra field 1" />
<EditText
android:id="@+id/edit_extra2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:hint="Extra field 2" />
<EditText
android:id="@+id/edit_extra3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:hint="Extra field 3" />
</LinearLayout>
然后在主页面里面添加ViewStub在某个你想要它出现的位置:
<include
layout="@layout/cancel_ok"/>
<ViewStub
android:id="@+id/view_stub"
android:layout="@layout/extra"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/button3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="add" />
看效果,点击add按钮后,实现显示这三个edittext
button监听里面:
ViewStub viewStub = (ViewStub) findViewById(R.id.view_stub);
if (viewStub != null) {
View inflatedView = viewStub.inflate();
editExtra1 = (EditText) inflatedView.findViewById(R.id.edit_extra1);
editExtra2 = (EditText) inflatedView.findViewById(R.id.edit_extra2);
editExtra3 = (EditText) inflatedView.findViewById(R.id.edit_extra3);
}