sockeqwe
sockeqwe

Reputation: 15929

Custom View with custom xml attribute: How to refeference a layout

does anybody know, how to get a referenced xml layout, programmatically (in code) for my custom widget. I have already created a custom declare-styleable, with my desired attributes and I know how to get ohter xml attribute values, like string or integers.

What I want to do is something like this:

<MyCustomView
    xmlns:my="http://schemas.android.com/apk/res-auto"
    id="@+id/view"
    my:headerLayout="@layout/my_fancy_layout"
    />

So I want to retrieve my_fancy_layout programmatically and inflate that layout in the code of MyCustomView.

Any idea how to do that?

Edit: I guess I can retreive the resource id with

int resId = attrs.getAttributeResourceValue(androidns, "headerLayout", 0);

But whats the correct namespace if I MyCustomView is a library project and if I would like to use

xmlns:my="http://schemas.android.com/apk/res-auto"

Upvotes: 2

Views: 376

Answers (2)

sockeqwe
sockeqwe

Reputation: 15929

Ok, i found the solution by myself:

you have to retrieve a TypedArray from yout AttributeSet.

than you can access your desired resource id with something like this:

TypedArray attrs = ... ;
int headerRes = attrs.getResourceId(R.styleable.MyCustomWidget_headerLayout, -1);

than you can inflate like usually:

LayoutInflater.from(context).inflate(headerRes, this);

Upvotes: 2

etienne
etienne

Reputation: 3206

You can indeed inflate your layout in the constructor of your custom view:

public class MyCustomView extends /* LinearLayout, RelativeLayout, etc. */ {
    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }
    public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView(context, attrs);
    }
    protected void initView(Context context, attrs) {
        LayoutInflater.from(context).inflate(attrs.getAttributeResourceValue("http://schemas.android.com/apk/res-auto", "headerLayout", 0), this, true);
    }
}

Upvotes: 0

Related Questions