'Android Custom Attr is not in my AttributeSet
I have a custom attribute defined as such in my res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="hint" format="string" />
<declare-styleable name="McEditText">
<attr name="hint" />
</declare-styleable>
</resources>
I refer to it in McEditText.kt
class McEditText @JvmOverloads constructor(
context: Context,
attrs: AttributeSet
) : ConstraintLayout( context, attrs) {
private var _layout :ConstraintLayout
private var _editText: EditText
var hint :String = ""
init {
context.theme.obtainStyledAttributes(attrs, R.styleable.McEditText, 0, 0).apply {
try {
hint = getString(R.styleable.McEditText_hint).toString()
} finally {
recycle()
}
_layout = inflate( context, R.layout.layout_mcedittext, this@McEditText ) as ConstraintLayout
_editText = _layout.findViewById(R.id.mc_edit_text)
_editText.hint = hint
for (i in 0 until attrs!!.attributeCount) {
Log.e("ATTRS", i.toString() + ": " +
attrs.getAttributeName(i) + " " + attrs.getAttributeValue(i) ) }
}
}
}
Then in my XML I have
<?xml version="1.0" encoding="utf-8"?>
<!-- Merge into a ConstraintLayout -->
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/mc_edit_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
custom:hint="poofy"/>
</merge>
Running the code you would expect to see a text area with a hint of "poofy". But no, the hint is "null"! (So much for kotlin's null safety). The log shows this:
E/ATTRS: 0: id @2131296465
E/ATTRS: 1: layout_width -1
E/ATTRS: 2: layout_height -2
E/ATTRS: 3: layout_constraintStart_toStartOf 0
E/ATTRS: 4: layout_constraintTop_toTopOf 0
As you can see the custom hint attr is missing. Why?
(And yes, I tried it with the format="string" inside the local attr rather than referred to from the outer scope. Same deal)
Solution 1:[1]
See the comment above. Embarassing mistake.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Clark Battle |
