canvas教程

写出高效清晰Layout布局文件的一些技巧(2)

字号+ 作者:H5之家 来源:H5之家 2017-01-07 09:01 我要评论( )

你只需要简单的在2个TextView之间添加一个Space就可以了 TextView android:layout_width="match_parent"android:layout_height="wrap_content"Space android:layout_width="match_parent"android:layout_height="10

你只需要简单的在2个TextView之间添加一个Space就可以了

<TextView android:layout_width="match_parent" android:layout_height="wrap_content" <Space android:layout_width="match_parent" android:layout_height="10dp"/>//添加间距 <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/gotham_city_description"/> 5.Use <include/> and <merge/>

使用<include/>和<merge/>标签

重用布局是一个保持app一致的好方法,这样以后有改变的话只要改一个文件就可以了,Android提供了<include/>标签帮你重用布局。

例如你现在决定创建有一个logo图片居中的酷炫Toolbar工具栏,然后你想要添加到每个页面中,下面是Toolbar效果:


toolbar

下面是batman_toolbar.xml代码

<android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:theme="@style/AppTheme.AppBarOverlay" app:popupTheme="@style/AppTheme.PopupOverlay"> <ImageView android:layout_width="wrap_content" android:layout_height="@dimen/batman_logo_height" android:layout_gravity="center" android:src="@drawable/batman_logo_transparent"/> </android.support.v7.widget.Toolbar>

你可以复制粘贴这些代码到每个Activity,但是不要这么做,在编程中有一个重要的规则:当你复制粘贴,那你就是在做错误的事。在这种情况下你可以用<include/>标签在多个界面重用这个布局。

<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout 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" android:fitsSystemWindows="true" android:background="@android:color/white" tools:context=".MainActivity"> <include layout="@layout/batman_toolbar"/> </android.support.design.widget.CoordinatorLayout>

用<include/>标签你可以只用一行代码在app的每个页面添加你的toolbar,任何改变都会自动更新到所有页面。

除了<include/>,<merge/>也常用来从你的view层次结构中减不必要的view,它会移除没必要的嵌套的layouts,例如,如果被包含布局文件的根是一个LinearLayout,然后你把它include包含在另外一个LinearLayout里面,2个嵌套的LinearLayouts是没有必要的,这个嵌套的layout没有任何作用除了影响UI性能。在这种情况下可以用<merage/\>来替换被包含布局的根LinarLayout 移除不必要的view.

关于<include/>和<merge/>的更多信息你可以查看官方文档

Don’t always play by the rules

上面的技巧不用当做规则

我希望这5个技巧可以帮你写出更好更简单的布局layout,但是不要把这些技巧当是规则,它们更像是指南。总有一些情况下你没法使用这些技巧,只能通过增加布局的复杂性来解决。在这种情况下,在添加更多view之前,你可以考虑自定义View试的找到更简单的解决方法。只要记住一件事,在你的视图层次添加一个view代价是不可小嘘的,它会影响你的app加载速度。

谢谢Ana和oFca对文章进行校对。

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 提高Interface Builder高效工作的8个技巧

    提高Interface Builder高效工作的8个技巧

    2016-09-03 18:02

  • 写出卓越的jQuery插件的10个技巧

    写出卓越的jQuery插件的10个技巧

    2015-10-15 10:10

网友点评
"