[英]How to build parameterized custom layout?
My app is all about manipulating and showing different views of a particular entity. 我的应用程序全部是关于操纵和显示特定实体的不同视图的。 I have a class called
Item
that defines an entity in my app. 我有一个名为
Item
的类,该类在我的应用程序中定义了一个实体。 I have created a custom layout that knows how to render a particular version of Item
s: 我创建了一个自定义布局,该布局知道如何呈现
Item
的特定版本:
public class MyItemLayout extends FrameLayout {
public MyItemLayout(Context context, AttributeSet attrs) { ... }
}
I would like to be able to reference this in XML: 我希望能够在XML中引用它:
<MyItemLayout .../>
What I don't understand yet is: 我还不了解的是:
Item
instance for the element? Item
实例? I can't do that in XML (or can I?), so how would I do it in code? Thanks. 谢谢。
One way for you to reference a custom component (View or ViewGroup) is to have the full package name, like <com.foo.bar.MyItemLayout>
引用自定义组件(View或ViewGroup)的一种方法是使用完整的包名称,例如
<com.foo.bar.MyItemLayout>
One option also to pass data from declaration in XML is using the AttributeSet
in the constructor. 从XML声明中传递数据的一种方法是在构造函数中使用
AttributeSet
。 If you set an attribute in XML you can fetch it using the methods from this class ( getFloatValue()
for example). 如果以XML设置属性,则可以使用此类的方法
getFloatValue()
例如getFloatValue()
来获取属性。
So: Step 1: Do something like <com.foo.bar.MyItemLayout item="xxxx"></com.foo.bar.MyItemLayout>
Step 2: In MyItemLayout
constructor call attrs.getFloatValue()
(or whatever type you wish) to get the data 因此:步骤1:做类似
<com.foo.bar.MyItemLayout item="xxxx"></com.foo.bar.MyItemLayout>
步骤2:在MyItemLayout
构造函数中,调用attrs.getFloatValue()
(或您想要的任何类型attrs.getFloatValue()
)获取数据
Hope it helped JQCorreia 希望它对JQCorreia有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.