Home > Net >  How do you get "style:" tag value in a Custom View
How do you get "style:" tag value in a Custom View

Time:09-29

In my custom view, I want to read a value of a style tag. For instance, my CustomButton could have ButtonStyleLarge or ButtonStyleSmall, and I need to read that value in my init{ } block

  <CustomButton
        style="@style/ButtonStyleLarge" // <- this one
        android:id="@ id/buttonSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/User.Button.Save"/>

My custom view:

 class CustomButton @JvmOverloads constructor(
     context: Context,
     attrs: AttributeSet? = null,
     defStyleAttr: Int = R.style.ButtonStyleLarge
 ) : AppCompatButton(context, attrs, defStyleAttr) {
 
     init {
         when (explicitStyle) {
             R.style.ButtonStyleLarge -> {
                 // do something to the view
             }
             R.style.ButtonStyleSmall -> {
                 // do something to the view
             }
         }
     }
 }

There is this function -> getExplicitStyle() (or just explicitStyle in Kotlin) but it is added in API 29. Need to support much lower SDKs.

Reading defStyleAttr at this point will just return the default value set in the constructor.

There is also an option for reading the "android" tag value like this (e.g. for maxLength):

attrs.getAttributeIntValue("http://schemas.android.com/apk/res/android", "maxLength", 100)

Is there something similar for just style?

CodePudding user response:

You can probably get away by using AttributeSet.getStyleAttribute()

If this is your custom view

<CustomButton
    style="@style/MyStyle"
    ...

You can do this in the constructor

class CustomButton @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = R.style.ButtonStyleLarge
) : AppCompatButton(context, attrs, defStyleAttr) {

    init {
        // Retrieve style resource ID
        val explicitStyle = attrs?.getStyleAttribute() ?: NO_ID

        when (explicitStyle) {
            R.style.ButtonStyleLarge -> {
                // do something to the view
            }
            R.style.ButtonStyleSmall -> {
                // do something to the view
            }
        }

        // If you need the actual name of the Style resource...
        val styleName = context.resources.getResourceEntryName(explicitStyle)
        //  styleName = "MyStyle"

    }
}
  • Related