Search code examples
androidkotlinandroid-layoutmaterial-design

Getting attributes value declare in xml before inflating


I am creating a custom button MyButton extending MaterialButton. The use-case is that there are 2 sizes of button large and small, Large button will be of full width (similar to match_parent) and small button will have some minWidth lets say 100dp, and most importantly they will have different padding and different text sizes. While writing my custom class for MyButton how can I check what is the layout_height and layout_width mentioned in xml so that I can take appropriate action for setting the proper UI ?

I tries getting the view height and width , but they will are coming as 0 coz they not completely laid by that time. I also tried using doOnLayout{ } but this is also not getting called in MyButton class. I also tried a custom attributes for button_size and based on that setting the layout params, but also not working.

So I am hoping if somehow I can get what are the thing declared in the xml (mainly layout_width) so i can update the other property accordingly.

e.g.

open class MyButton @JvmOverloads constructor(
     context: Context,
     private val attributeSet: AttributeSet? = null,
     private val styleAttribute: Int = com.google.android.material.R.attr.materialButtonStyle) :
    MaterialButton(context, attributeSet, styleAttribute) {
       init{
          attributeSet?.let { parseAttr(it) }
       }

       private fun parseAttr(attr: AttributeSet) {

           if (/* need to check if the declared layout_width is match_parent*/){
                // set some padding and text style
           } else {
                // set some different padding and texy style
           }

        }
    }

Solution

  • To get the attributes defined in xml for any custom view, we can use the AttributeSet getting from the constructor.

    This is how I did it.

      for (i in 0 until attributeSet.attributeCount) 
      {
        if (attributeSet.getAttributeName(i) == "layout_width" && (attributeSet.getAttributeValue(i) == LayoutParams.MATCH_PARENT.toString())) 
        {
          // this indicate that layout_width is set to match_parent
        }
      }
    

    In the similar way one can get any attributes and its value defined in xml

    Note: in the attributeCount and the list of attribute we are not getting those whose value is setting through data binding