Valentin Stoychev
Valentin Stoychev

Reputation: 85

Custom Type attributes for a custom android view

I want to create a custom Android View (MyCustomView). In this View I want to have a property of a custom Type (MyCustomType). Similar to this:

MyCustomView extends LinearLayout {

    private MyCustomType prop1;

    public MyCustomType getProp1()
    {
        return this.prop1;
    }

    public void setProp1(MyCustomType value)
    {
        this.prop1 = value;}
    }
}

So far so good. But now I want to be able to set the value of this property from XML. I can create a custom attribute with string, int, reference format, but I do not see how to define this attribute to be of MyCustomType format. I image something similar to this:

<declare-styleable name="MyCustomView">
    <attr name="prop1" format="MyCustomType"/>
</declare-styleable>

Is this possible somehow? Or custom type attributes are possible to be set only from code behind?

Thank you!

Upvotes: 1

Views: 155

Answers (2)

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

You cannot use own property types with android framework. You can come with own proprties based on available types but that's it. Not sure what type you got in mind in your case, but in most cases whatever that custom thing is, it could be solved by available primitives.

Upvotes: 0

akelix
akelix

Reputation: 410

I don`t really understand why you need this. but you can use format="String" and write full class name in property field in your layout. For example: custom:prop1="com.example.MyCustomType"

then in constructor of your View:

TypedArray a = context.getTheme().obtainStyledAttributes(
    attrs,
    R.styleable.MyCustomView,
    0, 0);
String className = a.getString(R.id.prop1);
Class<MySustomType> c = Class.forName(className);
MySustomType prop = c.newInstance();
setProp1(prop);

Upvotes: 1

Related Questions