0

I have a custom view which extends RelativeLayout. I have some custom attrs in attrs.xml. Is there a way to obtain common android attrs like android:clickable like we do with custom attributes?

class MyView(context: Context, attributeSet: AttributeSet?): RelativeLayout(context, attributeSet) {
  init {
      val attrs = context.obtainStyledAttributes(attributeSet, R.styleable.MyView)
    
      if (attrs.getBoolean(android.R.attr.clickable, true)) {
          ...
      }
    
      attrs.recycle()
  }

}

This compiler accepts, but it crashed on runtime. Anyone have come across similar use case? I would like to avoid creating duplicate attrs for custom view which are already defined in SDK.

parohy
  • 2,070
  • 2
  • 22
  • 38
  • By extending `RelativeLayout` the custom view inherits its attributes. You usually don't need to "touch" them unless your intention is to change the parent's behaviour which, actually, might be confusing/unpredictable for a user/developer. – Onik Oct 27 '20 at 09:15
  • check https://stackoverflow.com/a/7913610/5909412 – P.Juni Oct 27 '20 at 11:48
  • Why is crashing? What is the stacktrace? – cutiko Oct 27 '20 at 12:32

2 Answers2

0

More or less, the answer was in front of me the whole time. One thing that I had to understand, that when you create a stylable its basically an IntArray. Now when you obtain attributes and pass yout stylable reference, it maps attributes bassed on its definition. So in order to obtain other attributes, which are not declared in your local attrs, like those android: which are in the SDK, you need to pass those references in as an IntArray:

class MyView(context: Context, attributeSet: AttributeSet?): RelativeLayout(context, attributeSet) {
    init {
        val attrs = context.obtainStyledAttributes(attributeSet, intArrayOf(android.R.attr.clickable))

        if (attrs.getBoolean(0, true)) {
            ...
        }

        attrs.recycle()
    }
}
parohy
  • 2,070
  • 2
  • 22
  • 38
-1

Yeah, probably this one should work

at attrs.xml you should declare smth like that

    <declare-styleable name="MyCustomView">
        <attr name="android:clickable" />
    </declare-styleable>

And at your MyCustomView class you should obtain desired properties from typed array like:

val clickable = typedArray.getBoolean(R.styleable.MyCustomView_android_clickable, false)