Custom xml attribute for @layout link

I would like to create my own view with my own xml attributes. I would like to specify the header layout to be inflated in my custom xml view, something like this:

<com.example.MyCustomWidget
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:headerLayout="@layout/my_header"
   />

      

Is this possible and how to get the layout resource from TypedArray

?

So in the end, I would like to do something like this:

class MyCustomWidget extends FrameLayout { 


public ProfileTabLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ProfileTabLayout);

    int headerLayout = a.getLayout(R.styleable.MyCustomView_headerLayout, 0); // There is no such method

   a.recycle();

   LayoutInflater.from(context)
        .inflate(headerLayout, this, true);

  }

}


<?xml version="1.0" encoding="utf-8"?>
<resources>
  <declare-styleable name="MyCustomWidget">
    <attr name="headerLayout" format="reference" />
  </declare-styleable>
</resources>

      

+3


source to share


1 answer


You must first create your own field. To do this add the code belowres/values/attrs.xml

<declare-styleable name="MyCustomView">
    <attr name="headerLayout" format="reference" />
</declare-styleable>

      

Then in your custom view, you can get that value in the constructor



public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    ...
    TypedArray a = context.getTheme().obtainStyledAttributes(
            attrs,
            R.styleable.MyCustomView,
            defStyle, 0
    );

    try {
        int headerLayout = a.getResourceId(R.styleable.MyCustomView_headerLayout, 0);
    } finally {
        a.recycle();
    }
    ...
}

      

Here you can inflate headerLayout

withLayoutInflater

+10


source







All Articles