2012-02-23 40 views
1

我想將包含幾個Textviews,ImageViews和ProgressViews的視圖類定義爲一個DisplayClass,並將它們作爲元素。在一個視圖類中組合了多個UI元素

背後的想法是,可以在XML中多次重複使用DisplayClass,並輕鬆訪問/更新不同的DisplayClass實例。

在XML它看起來像一個定製的小工具,多次使用,喜歡這裏......

<myDisplayClass 
       android:id="@+id/id1" 
       android:layout_width="60dp" 
       android:layout_height="wrap_content" 
       android:leftText ="x1..." 
       android:midText = "y1.." 
       android:topText = "z1.." 
       ...and other fields /> 

    <myDisplayClass 
       android:id="@+id/id2" 
       android:layout_width="60dp" 
       android:layout_height="wrap_content" 
       android:leftText ="x2..." 
       android:midText = "y2.." 
       android:topText = "z2.." 
       ...and other fields /> 

<myDisplayClass 
       android:id="@+id/id3" 
       android:layout_width="60dp" 
       android:layout_height="wrap_content" 
       android:leftText ="x3..." 
       android:midText = "y3.." 
       android:topText = "z3.." 
       ...and other fields /> 

<myDisplayClass 
       android:id="@+id/id_n" 
       android:layout_width="60dp" 
       android:layout_height="wrap_content" 
       android:leftText ="x.n.." 
       android:midText = "y.n." 
       android:topText = "z.n." 
       ...and other fields /> 

雖然它是基於一個佈局display_class.xml定義只有一次佈局。

非常感謝任何想法,提示或可用的示例/教程。

回答

1

要重新使用一個共同的XML代碼:

,你可以在不同的佈局定義它說commonlayout.xml這將有線性/相對佈局等作爲家長與所有你在那裏要的意見。

在要使用該佈局的任何XML代碼,你可以只使用

<include layout="@layout/commonlayout" />

PS:我沒有看到你需要在這個問題定義myDisplayClass你給了,如果你只是要使用默認的EditText/TextViews /小工具等等。或者你可以解釋它,如果在答覆中提到不是你要找的人..

編輯: 在評論中指定概率後:

View layout1 = findViewById(R.id.layout1); 
TextView tv = (TextView)layout1.findViewById(R.id.commonTextView); 

類似地用於第二佈局另一個的TextView

TextView tv2 = (TextView)layout2.findViewById(R.id.commonTextView); 
+0

可以說在這個包括有3個TextViews。因此,在編寫後跟另一個不能訪問第一個或第二個TextView,因爲不確定的TextViews具有相同的ID。只有頂層元素有不同的ID,例如commonlayout1和2--這意味着當訪問內容時不能使用這個 - 或者我在這裏錯過了什麼? – user387184 2012-02-23 18:34:50

+0

檢查出更新的答案... – 2012-02-23 18:54:28

+0

編輯後 - 謝謝,用這個可以訪問字段。我現在需要的只是舒適地訪問它們,而不必在代碼中對XML中的ID進行硬編碼。很高興能這樣說:「對於layout_x中的tmp_layout做tv = tmp_layout ....」順便說一句,我也找到了「一般」解決方案。它更復雜但非常靈活。創建View的子類並實現所有的方法esp繪圖canvas上的所有元素都是有趣的:-) – user387184 2012-02-23 19:26:11

相關問題