在我的自定义视图上重用标准的安卓属性

15

我正在创建一个自定义组合视图,其布局如下

<merge xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="horizontal">

    <TextView
        android:id="@+id/label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <EditText
        android:id="@+id/edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:singleLine="true"/>

</merge>

正如您所看到的,它只是一个TextView和一个EditText。 我希望能够为我的自定义视图提供属性,这些属性将转发到TextViewEditText中。例如:

<codeguru.labelededittext.LabeledEditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:label="@string/label"
    app:hint="@string/hint"/>
我已经想出如何分别将这些字符串属性转发到TextViewEditText中:

我已经想出如何将这些字符串属性分别转发到TextViewEditText中:

    TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.LabeledEditText,
            0, 0);

    try {
        label.setText(a.getString(R.styleable.LabeledEditText_label));
        edit.setHint(a.getString(R.styleable.LabeledEditText_hint));
    } finally {
        a.recycle();
    }

现在我也想设置EditTextinputType。如果我创建一个<attr name="inputType" format="flag">标签,我是否需要填充所有可能的标志值?是否有一种方法可以重复使用EditText已声明的值?


你的描述不清楚。你是想说你希望所有组件中都有相同的属性标签吗? - prashantwosti
@prashantwosti 不,我想要一个label属性,它设置了TextViewandroid:text和一个hint属性,它设置了EditTextandroid:hint。这些很简单,因为它们只是字符串。然而,我还想要一个inputType属性,它设置了EditTextandroid:inputType。但我不想为所有可能的值重新编写代码。 - Code-Apprentice
我会建立一个恰当的 SSCCE 以更好地进行说明。 - Code-Apprentice
可能是重复的问题:如何在自定义视图中使用标准属性android:text?(https://dev59.com/mmMl5IYBdhLWcg3w7qlq) - Code-Apprentice
1个回答

3

你可以通过以下方式获得:

int[] values = new int[]{android.R.attr.inputType};
TypedArray standardAttrArray = getContext().obtainStyledAttributes(attrs, values);
try {
    mInputType = standardAttrArray.getInt(0, EditorInfo.TYPE_NULL);
} finally {
    standardAttrArray.recycle();
}

1
这似乎接近我想要的。然而,它实际上没有设置包含在我的自定义视图中的EditTextinputType。此外,我宁愿将所有属性直接转发给该EditText,让它自己提取它们,而不是编写提取每个属性的所有代码行。 - Code-Apprentice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接