布局优化

Android布局是整个UI的基础,好的布局不但能够带来好看的效果,同样会带来效率上的提高。一般情况下我们需要尽可能的减少布局的层次,避免没完没了的一层一层的嵌套。Android SDK的tools目录下的hierarchyviewer可以帮助我们查看布局层次,提出一些修改意见,当然使用的时候你的程序得跑在模拟器上才行。
[size=medium][color=red]merge标签的使用:[/color][/size]

<?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">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@drawable/welcome"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/green_btn_selector"/>
</merge>

一般情况下我们都能够将顶层是FrameLayout的布局替换为merge,但是merge标签的使用还是有一些限制:
1.只能作为一个布局的根节点。
2.使用LayoutInflater.inflate加载布局的时候需要使用View inflate(int resource, ViewGroup root, boolean attachToRoot)为其指定一个ViewGroup以及设置attachToRoot为true。
[size=medium][color=red]ViewStub的使用[/color]:[/size]
有时候我们需要动态的设置一个控件或者布局的显示。通常的做法是设置visibility属性,当满足某个条件时调用setVisibility(View.VISIBLE)显示出来。这样做逻辑上比较简单,但是布局初始化时就算控件没有显示出来,依然需要被实例化,ViewStub则可以做到只在调用inflate()方法的时候才被实例化。

<ViewStub
android:id="@+id/viewstub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout="@layout/view_show_layout"/>


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

当调用viewStub.inflate()的时候,view_show_layout才被实例化并显示在UI界面上。
需要注意的是ViewStub一旦调用inflate()显示出布局以后就不能再通过它控制布局的隐藏了,如果你的布局需要不断地隐藏显示,那么ViewStub就不再合适了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值