【问题标题】:Unable to change background image in custom EditText class无法更改自定义 EditText 类中的背景图像
【发布时间】:2021-02-02 12:36:10
【问题描述】:

我有一个自定义 EditTextClass 用于我的应用程序上的所有 EditTexts -

Class CustomEditText : EditText {
...
}

我想更改背景图像,以便它应该反映在此 CustomEditText 的所有用法中。

我试过了-

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

还有这个-

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

两种方式都行不通。谁能告诉我正确的解决方案是什么?

【问题讨论】:

    标签: android android-edittext android-custom-view


    【解决方案1】:

    绘制drawable时需要setBoundsdrawable
    所以你应该让你的draw方法像这样。

    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)
    }
    

    【讨论】:

    • 我已经在我的环境中测试了上层代码。它完美地工作。然后你能分享更多代码吗?所以我可以调试。你检查过你的可绘制资源吗?
    • 我很抱歉。这是我的错。您的代码有效。
    • 很高兴为您提供帮助。
    • @Daniel.Wang super.onDraw(canvas) 必须在底部,不是吗?
    【解决方案2】:

    首先绘制到canvas 并将canvas 传递给parent,意思是super.onDraw 应该在底部

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

    【讨论】:

      【解决方案3】:

      在我看来,您应该覆盖onDraw 方法,因为这可能会在您的操作之前调用super.onDraw(canvas) 时导致问题(您的drawable 可能会覆盖文本、点击、可绘制元素等) .).

      我做了一个演示,对我有用:

      class CustomEditText : AppCompatEditText {
          constructor(context: Context) : super(context) {
              init()
          }
          constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
              init()
          }
          constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context,
                                                                                         attrs,
                                                                                         defStyleAttr) {
              init()
          }
      
          private fun init() {
              setBackgroundResource(R.drawable.new_drawable)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-23
        • 1970-01-01
        • 2012-02-12
        • 2020-09-30
        • 1970-01-01
        • 2022-06-12
        • 2023-03-23
        • 2012-05-08
        相关资源
        最近更新 更多