Home > Software engineering >  How can I have reference for drawableTop of a Button?
How can I have reference for drawableTop of a Button?

Time:01-06

I declared a drawable inside my Button and I want to get a reference for that because I created a method where I display a Dialog, extract the text and drawable of that button and use it to change the text and icon of a dialog dynamically.

Please do check this snippet:

private fun showProductDialog(button : Button){
        //extract product info selected from button

        //show dialog
        val dialog = Dialog(this)
        dialog.setContentView(R.layout.dialog_product)
        //set text and icon
        val titleLayout = dialog.findViewById<LinearLayout>(R.id.ll_product_label)
        val titleText = titleLayout.findViewById<HelveticaBoldTextView>(R.id.tv_category_click)
        val titleIcon = titleLayout.findViewById<ImageView>(R.id.iv_product_icon)

        //get text of button, set to titleText
        titleText.text = button.text.toString().uppercase()

        //extract drawableTop of Button then
        //set image for titleIcon = drawable in Button
        
        dialog.show()
    }

Edited, I added this line inside my showProductDialog() but the issue is it rescaled my button's image too when clicked. No errors but my guess is that the button.compoundDrawables not only get all the drawables, but also set the image on my button. Since my image in dialog is set to 24x24 dp, my button clicked also set to 24x24.

//extract drawableTop of Button then
        //set image for titleIcon = drawable in Button
        val drawables = button.compoundDrawables
        titleIcon.setImageDrawable(drawables[1])

CodePudding user response:

To get DrawableTop you can use this

val compoundDrawables = button?.compoundDrawables
val drawable = compoundDrawables?.get(1)

To set DrawableTop you can use this

 button?.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.icon, 0, 0);
  •  Tags:  
  • Related