从属性集中获取提示属性值



我已经覆盖了此链接中给出的EditText。

现在,在布局中声明此字段时,我正在使用

<com.and.ab1209.ClearableEditText
android:id=”@+id/edit_text_clearable”
android:layout_width=”fill_parent”
android:hint="My Hint Goes here"
android:layout_height=”wrap_content” />

如何在这些构造函数中的任何一个中检索此提示值。

 public ClearableEditText(Context context, AttributeSet attrs, int defStyle){...}
 public ClearableEditText(Context context, AttributeSet attrs){...}

我该怎么做?

可以通过在

视图构造函数中执行以下操作来访问标准 xml 属性:

final String xmlns="http://schemas.android.com/apk/res/android";
//If you had a background attribute this is the resource id
int backgroundResource = attrs.getAttributeResourceValue(xmlns, "background", -1);
//This is your views hint
String hint = attrs.getAttributeValue(xmlns, "hint");

视图是否继承自 TextView 并不重要,如果使用 android:hint 指定提示,则可以在自定义视图中访问该提示。

您无法访问"android"属性。调用构造函数后可以使用getHint() super()。如果要创建自己的属性,请遵循本教程。

构造函数中使用this.getHint()

您可以使用 android 命名空间的属性,方法是在属性集中定义它。例如:

attrs_custom_input_field.xml

<resources>
    <declare-styleable name="CustomInputField">
        <attr name="android:hint" format="string" />
        <attr name="android:text" format="string" />
    </declare-styleable>
</resources>

CustomInputField.kt

class CustomInputField : ConstraintLayout {
    // ....
    // init called from all constructors
    private fun init(attrs: AttributeSet?, defStyle: Int) {
        val a = context.obtainStyledAttributes(
                attrs, R.styleable.CustomInputField, defStyle, 0)
        val hint = a.getString(R.styleable.CustomInputField_android_hint)
        val text = a.getString(R.styleable.CustomInputField_android_text)
        a.recycle()
        // use hint and text as you want
    }
}

您应该只定义现有属性,否则,您将在编辑器中收到错误

最新更新