从AttributeSet中获取Hint属性值

3
我已经按照 该链接 中的说明重写了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){...}

我该如何做到这一点?

4个回答

4

您可以通过在视图构造函数中执行以下操作来访问标准的 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指定提示,它也将在您的自定义视图中可用。


1

您无法访问“android”属性。在调用super()构造函数后,可以使用getHint()。如果您想创建自己的属性,请参考此教程


由于ClearableEditText扩展了RelativeLayout,因此我无法使用getHint()方法。 - RPB
你应该创建自己的属性并使用它。 - Jin35
这是一个相当冗长的过程,需要更多的代码,而我不想遵循那样的方式,所以我只是请求这个东西。 - RPB

1

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


由于ClearableEditText扩展了RelativeLayout,因此我无法使用getHint()方法。 - RPB
哦,你必须扩展EditText - PC.
这是不可能的,因为我将使用RelativeLayout作为最外层的布局。如果那样的话,我为什么要自定义EditText呢? - RPB

0

您可以使用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
    }
}

你应该只定义已存在的属性,否则在编辑器中会收到错误提示。


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