重新运行并打开HierarchyViewer查看布局结构,发现之前嵌套的一个RelativeLayout就没有了,这就是使用merge的效果,能降低布局的嵌套层次。 3、< ViewStub />的使用也许有不少同学对ViewStub还比较陌生,首先来看看ViewStub在官方文档里是怎么介绍的:
大致意思是:ViewStub是一个不可见的,能在运行期间延迟加载的大小为0的View,它直接继承于View。当对一个ViewStub调用inflate()方法或设置它可见时,系统会加载在ViewStub标签中引入的我们自己定义的View,然后填充在父布局当中。也就是说,在对ViewStub调用inflate()方法或设置visible之前,它是不占用布局空间和系统资源的。它的使用场景可以是在我们需要加载并显示一些不常用的View时,例如一些网络异常的提示信息等。 我们新建一个xml文件用来显示一个提示信息: xml common_msg.xml<RelativeLayout mlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="@android:color/white" android:padding="10dip" android:text="Message" android:textColor="@android:color/black" /> </RelativeLayout> 然后在main.xml里面加入ViewStub的标签引入上面的布局: xml 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:background="@android:color/darker_gray" android:layout_height="match_parent" > <include layout="@layout/common_navitationbar" /> <ViewStub android:id="@+id/msg_layout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout="@layout/common_msg" /> </merge> 修改MainActivity.java的代码,我们这里设置为点击右上角按钮的时候显示自定义的common_msg.xml的内容。 java MainActivity.javapublic class MainActivity extends Activity { private View msgView; private boolean flag = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.findViewById(R.id.rightButton).setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { System.out.print("111"); if(flag){ showMsgView(); }else{ closeMsgView(); } flag = !flag; } }); } private void showMsgView(){ if(msgView != null){ msgView.setVisibility(View.VISIBLE); return; } ViewStub stub = (ViewStub)findViewById(R.id.msg_layout); msgView = stub.inflate(); } private void closeMsgView(){ if(msgView != null){ msgView.setVisibility(View.GONE); } }} 代码中我们通过flag来切换显示和隐藏common_msg.xml的内容,然后我们运行一下并点击右上角按钮来切换,效果如下: 总结好了,到目前为止,我们就介绍了Android中关于布局优化的一些内容以及工具HierarchyViewer的使用。将前文提及的布局原则再列一下,欢迎大家补充更多的关于Android布局优化的实用原则。
作者新浪微博:唐韧_Ryan |