Search code examples
androidandroid-edittextandroid-custom-view

Unable to change background image in custom EditText class


I have a Custom EditTextClass that Im using for all EditTexts on my App -

Class CustomEditText : EditText {
...
}

I want to change the background image, so that it should be reflected in all the usages of this CustomEditText.

I tried this -

override fun onDraw(canvas: Canvas ? ) {
    val d = AppCompatResources.getDrawable(mContext!!, R.drawable.new_drawable)
    d?.draw(canvas!!)
    super.onDraw(canvas)
}

and this -

fun init(context: Context ? , attrs : AttributeSet ? ) {
    background = ResourcesCompat.getDrawable(context!!.getResources(), R.drawable.new_drawable, null)
    setBackground(background)
}

Both the ways, don't work. Can anyone tell me what is the correct solution ?


Solution

  • You need to setBounds to drawable when draw drawable.
    So you should make your draw method like this.

    override fun onDraw(canvas: Canvas? ) {
        val d = AppCompatResources.getDrawable(context!!, R.drawable.new_drawable)
        d?.setBounds(0, 0, width, height)
        d?.draw(canvas!!)
        super.onDraw(canvas)
    }