2012-02-23 66 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