Arash Rohani
Arash Rohani

Reputation: 1014

Re-using android's built in xml attributes for a custom view

Let's say I have a custom view like this (This is just an example):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

        <EditText
            android:id="@+id/custom_view_edittext"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

</LinearLayout>

And I have created a custom attribute in attrs.xml:

<declare-styleable name="CustomView">
    <attr name="myCustomAttribute" />
</declare-styleable>

This is the code for this imaginary custom view:

public class CustomView extends LinearLayout {

    private String mCustomAttr;

    public CustomView(Context context) {
        super(context);
        configure(context);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setupAttributes(context, attrs);
        configure(context);
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setupAttributes(context, attrs);
        configure(context);
    }

    private void setupAttributes(Context context, AttributeSet attrs) {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CustomView);
        mCustomAttr = array.getString(R.styleable.CustomView_myCustomAttribute);
        array.recycle();
    }

    private void configure(Context context) {
        LayoutInflater.from(context).inflate(R.layout.custom_view_layout, this);
        EditText editText = findViewById(R.id.custom_view_edittext);
        // and so on
    }

}

What I want to do is use EditText-specific xml attribute as an attribute for my CustomView even though its root is LinearLayout. For example:

<path.to.package.CustomView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:myCustomAttribute="whatever"
    android:imeOptions="actionDone" />

Is there a way to do this without having to create every EditText attribute in my declare-styleable? Essentially I just want something like this for built in xml attributes in my setupAttributes function.

TypedArray array = context.obtainStyledAttributes(attrs, android.R.styleable.EditText);

Upvotes: 1

Views: 31

Answers (0)

Related Questions