【发布时间】:2011-07-12 18:34:04
【问题描述】:
我最近一直在学习合并和包含,但我有一个问题,我似乎也无法找到答案。假设我有一个布局,它定义了我想添加到多个布局的标题组件。但是,我想更改每个包含使用的每个标题的标题或图标。例如说我有以下布局:
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@style/menu_header">
<Button android:id="@+id/backButton"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/button"
android:text="@string/back"/>
<TextView style="@style/headerTitle"
android:layout_centerInParent="true"
android:text="${title}"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</RelativeLayout>
然后我可以在其他布局中使用:
<LinearLayout ...>
<include android:id="@+id/searchHeader" layout="@layout/shared_header" title="Search"/>
...
</LinearLayout>
我知道我可以修改根元素的任何 layout_* 属性,但我是否可以定义其他属性来替换布局,例如本例中的“标题”,而无需创建自己的 View 子类,添加在值/资源等中声明样式的定义?
拥有这样的东西会使创建可重用视图变得如此简单,但我似乎找不到任何证据表明合并 + 包含是否可以做到这一点。
【问题讨论】:
-
我觉得如果你想改变这些视图的内容,你应该使用由这些视图组成的自定义视图。当您想在其他地方复制/粘贴视图/视图组时,包含的东西更多的是一种工具。
-
但是如果您只能复制和粘贴完全相同的代码,则 include 的用处有限。自定义视图需要更多的编写开销,添加自定义样式选项,创建代码以子类化视图等。如果我所做的只是调整嵌套元素的一些属性,似乎可以在不吃掉整个大象的情况下完成
-
我再次阅读了关于包含的快速“教程”(android-developers.blogspot.com/2009/02/…),似乎很清楚它只是一个简单的复制/粘贴,尤其是当您包含一个常见的“子-布局”有 2 种不同的布局(纵向和横向)。虽然我确实觉得你的想法很酷:/
标签: android view attributes include parameterized