【问题标题】:Is there a way to reuse attr inputType?有没有办法重用 attr inputType?
【发布时间】:2014-11-16 03:26:29
【问题描述】:

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

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

引起:java.lang.ArrayIndexOutOfBoundsException:

错误,因为我的 ViewGroup 中没有 inputType attr。
我也试过这个:

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

同样的错误。

有什么想法吗?谢谢!

【问题讨论】:

  • 能否贴出相关的代码位(XML 布局等)?
  • @curtisLoew 感谢您的回复。我找到了一种方法来做到这一点。看我的回答。谢谢。

标签: android attr


【解决方案1】:

我找到了办法。

将此添加到 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);
}

【讨论】:

  • if (inputType != EditorInfo.TYPE_NULL) { mEditTextView.setInputType(inputType); }
  • 作为魅力。
  • 注意:使用您的自定义视图名称 + _android_inputType 而不是 ClearableEditText_android_inputType。
猜你喜欢
  • 2022-01-26
  • 1970-01-01
  • 2012-08-29
  • 1970-01-01
  • 2017-08-07
  • 2022-06-10
  • 2022-01-16
  • 2013-11-13
  • 2012-11-20
相关资源
最近更新 更多