2012-08-01 54 views
1

我正在寻找一种方法来覆盖我在android中自己的XML视图。 所以我只需要指定一次设置(如背景,边框,默认内容)并再次使用它。Android:覆盖XML中的自己的XML视图

问题是我找不到任何关于它的东西。 (我发现的事情是关于XML使用Java类重写,这不是我想要的)

这是一些非工作的代码,但我希望它不够好向你解释:

main.xml: 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
    <field android:text="@string/str1" /> 
    <field android:text="@string/str2" /> 
    <field android:text="@string/str3" /> 
    <field android:text="@string/str4" /> 
    <field android:text="@string/str5" /> 
</LinearLayout> 

code representing field (field.xml): 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/field" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="@layout/field_background" 
    android:text="@string/default_string"/> 

正如你看到的领域本身曾经多次定义和使用一次定制。 (另一个字符串作为文本集)

这根本不起作用,但我希望有人知道一种方法来做出类似这样的工作。 (无编码,只是XML)

感谢, 丹尼斯

回答

2

我建议你设置一个风格。在main.xml

<style name="DefaultTextFieldStyle"> 
    <item name="android:id">@+id/field</item> 
    <item name="android:layout_width">fill_parent</item> 
    <item name="android:layout_height">wrap_content</item> 
    <item name="android:background">@layout/field_background</item> 
</style> 

然后:在res/values一些文件(通常styles.xml),添加一个样式为您现场

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
    <TextView style="@style/DefaultTextFieldStyle" 
     android:text="@string/str1" /> 
    <TextView style="@style/DefaultTextFieldStyle" 
     android:text="@string/str2" /> 
    <TextView style="@style/DefaultTextFieldStyle" 
     android:text="@string/str3" /> 
    <TextView style="@style/DefaultTextFieldStyle" 
     android:text="@string/str4" /> 
    <TextView style="@style/DefaultTextFieldStyle" 
     android:text="@string/str5" /> 
</LinearLayout> 

我只是复制你的价值观,但它是错误的,具有相同的android:id值对于布局中的多个视图,以布局作为背景很奇怪。

+0

我不认为编译器会让你在Style中定义'android:id',无论如何这个想法是正确的,我同意它。我还会添加样式的父项,以便“常见”TextField行为得到保证。 – Shine 2012-08-01 15:32:34

+0

@Shine - 我刚刚尝试定义一个包含'> @ + id/foo'的样式,编译器和Android Lint都非常满意。我没有测试id值是否实际应用于视图,但我不明白为什么它不会。 – 2012-08-01 15:38:48

+0

因为,正如你所说,有多个视图有相同的android:id值是错误的..我认为这是一个“概念”的错误,但从来不知道:) – Shine 2012-08-01 15:45:06

0

这里不需要自定义组件。如果我理解你的问题,风格应该足以做你想找的东西。

只需定义的LinearLayout内部TextViews的系列,并让他们从可以如所描述的here定义风格inheritate公用部分(layout_widthlayout_height等)。

唯一改变的部分将是android:text,根据需要