How to have Image and Text Center within a Button

后端 未结 12 2210
感动是毒
感动是毒 2020-12-02 15:48

I want to display TEXT and Icon on a Button.

+----------------------------+
|          Icon TEXT         |
+---------------------         


        
12条回答
  •  不思量自难忘°
    2020-12-02 16:08

    I made a custom component to solve this problem.

    Component class:

    class CustomImageButton @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = 0,
        defStyleRes: Int = 0
    ) : RelativeLayout(context, attrs, defStyleAttr, defStyleRes) {
    
        init {
            inflate(context, R.layout.custom_image_button, this)
    
            // Load the styled attributes and set their properties
            val typedArray = context.obtainStyledAttributes(
                attrs,
                R.styleable.CustomImageButton, defStyleAttr, 0
            )
    
            val src = typedArray?.getDrawable(R.styleable.CustomImageButton_cib_src)
            val text = typedArray?.getText(R.styleable.CustomImageButton_cib_text)
            val contentDescription = typedArray?.getText(R.styleable.CustomImageButton_cib_contentDescription)
    
            ivIcon.setImageDrawable(src)
            tvText.text = text
            ivIcon.contentDescription = contentDescription
    
            typedArray?.recycle()
        }
    }
    

    Component XML:

    
    
        

    The resources attributes, attrs.xml:

    
            
            
            
        
    

    Component use example:

    
    

提交回复
热议问题