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. I have created a custom layout that knows how to render 开发者_StackOverflow社区a particular version of Item
s:
public class MyItemLayout extends FrameLayout {
public MyItemLayout(Context context, AttributeSet attrs) { ... }
}
I would like to be able to reference this in XML:
<MyItemLayout .../>
What I don't understand yet is:
- How do I reference this in XML?
- How do I set the
Item
instance for the element? 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>
One option also to pass data from declaration in XML is using the AttributeSet
in the constructor. If you set an attribute in XML you can fetch it using the methods from this class (getFloatValue()
for example).
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
Hope it helped JQCorreia
精彩评论