`
HU555U
  • 浏览: 30597 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

布局优化

阅读更多
Android布局是整个UI的基础,好的布局不但能够带来好看的效果,同样会带来效率上的提高。一般情况下我们需要尽可能的减少布局的层次,避免没完没了的一层一层的嵌套。Android SDK的tools目录下的hierarchyviewer可以帮助我们查看布局层次,提出一些修改意见,当然使用的时候你的程序得跑在模拟器上才行。
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">
	<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。
ViewStub的使用
有时候我们需要动态的设置一个控件或者布局的显示。通常的做法是设置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就不再合适了。
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics