首页 > 解决方案 > 为自定义视图重新使用 android 的内置 xml 属性

问题描述

假设我有一个这样的自定义视图(这只是一个例子):

<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>

我在 attrs.xml 中创建了一个自定义属性:

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

这是这个虚构的自定义视图的代码:

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
    }

}

我想要做的是使用 EditText 特定的 xml 属性作为我的 CustomView 的属性,即使它的根是 LinearLayout。例如:

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

有没有办法做到这一点,而不必在我的可声明样式中创建每个 EditText 属性?本质上,我只想在我的setupAttributes函数中为内置的 xml 属性提供类似的东西。

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

标签: androidandroid-custom-viewandroid-custom-attributes

解决方案


推荐阅读