有没有一种方法可以重用attr inputType?

6

我有一个自定义的ViewGroup,其中包含一个EditText。我希望在xml中为EditText设置inputType。但是我不想重新定义输入类型。我该怎么做?

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyEditText);
a.getInt(android.R.attr.inputType, EditorInfo.TYPE_NULL);

错误,原因是我的ViewGroup中没有inputType属性。
我还尝试了这个方法:

Caused by: java.lang.ArrayIndexOutOfBoundsException:

int[] attrsReuse = new int[] { android.R.attr.inputType /* index 0 */};
Resources.Theme theme = context.getTheme();
TypedArray ta = theme.obtainStyledAttributes(attrsReuse);

同样的错误。
有什么想法吗?谢谢!

你可以发布相关的代码片段(XML布局等)吗? - Tadej
@curtisLoew 谢谢您的回复。我找到了一种方法来实现这个。请看我的答案。谢谢。 - android_su
1个回答

31

我找到了一种方法来做这件事。

将这个添加到 attrs.xml 文件中:

<declare-styleable name="MyEditText" >
    <attr name="android:inputType"/>
</declare-styleable>

将此内容添加到视图中以查看布局:

android:inputType="textPassword"

然后我可以在我的自定义视图类中获取这个属性:

int inputType = a.getInt(R.styleable.MyEditText_android_inputType, EditorInfo.TYPE_NULL);
if (inputType != EditorInfo.TYPE_NULL) {
    mInputEditText.setInputType(inputType);
}

3
如果(inputType != EditorInfo.TYPE_NULL),那么就将mEditTextView的输入类型设置为inputType。 - Francis Shi
运行得很好。 - Johnny Five
1
注意:请使用您的自定义视图名称 + _android_inputType 替换 ClearableEditText_android_inputType。 - Johnny Five

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