How to build parameterized custom layout?

506 Views Asked by At

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 a particular version of Items:

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:

  1. How do I reference this in XML?
  2. 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.

1

There are 1 best solutions below

0
On BEST ANSWER

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