我正在寻找一种在android中覆盖我自己的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)
谢谢,Dennis
我建议您设置一个样式。在res/values
中的某个文件(通常为styles.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>
然后在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">
<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
值是错误的,而且将布局作为背景也很奇怪。
如果没有代码,我不知道如何做你想做的事情。。我会定义自己的自定义组件。另请参阅自定义样式定义的不同文本视图的不同格式,其中显示了如何为您想要的文本视图设置样式。
这里不需要自定义组件。如果我理解你的问题,风格应该足以满足你的需求。
只需在LinearLayout中定义一系列TextView,并让它们从您可以在此处定义的样式中继承公共部分(layout_width
、layout_height
等)。
唯一可更改的部分将是android:text
,根据需要