DCoder
DCoder

Reputation: 3488

How to define custom drawable in xml and use its custom attributes

Aim :

  1. I have MyDrawable which extends to GradientDrawable.
  2. I have defined custom attribute for MyDrawable.
  3. I have created xml in res->drawable->test_drawable.xml which has my <drawable> resource.
  4. I am using custom defined attribute from step 2 in test_drawable.xml to pass values to MyDrawable.
  5. Use custom attributes passed from test_drawable.xml in MyDrawable.inflate() this part is not working

Problem :

In MyDrawable.inflate() I am not getting my custom attribute values defined in res->drawable->test_drawable.xml

MyDrawable:

class MyDrawable() : GradientDrawable() {
private var radiusPercentage : Int = 25

  override fun inflate(
    r: Resources,
    parser: XmlPullParser,
    attrs: AttributeSet,
    theme: Resources.Theme?
  ) {
super.inflate(r, parser, attrs, theme)
val a = r.obtainAttributes(attrs, R.styleable.MyDrawable)
// I am always getting 0 here. Checked with breakpoint in debug mode.
val radius = a.getInteger(R.styleable.MyDrawable_radiusPercentage, 0)
radiusPercentage = radius
}
}

Custom attribute:

<declare-styleable name="MyDrawable">
    <attr name="radiusPercentage" format="integer"/>
</declare-styleable>

res->drawable->test_drawable.xml

<?xml version="1.0" encoding="utf-8"?>
<drawable xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    class="com.test.app.RoundedCornersDrawable
    app:radiusPercentage="50" />

I am setting it on my container

binding.container.background =
      AppCompatResources.getDrawable(context, R.drawable.test_drawable)

Upvotes: 1

Views: 229

Answers (0)

Related Questions