2012-08-01 18 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,根據需要