当我想在 Kotlin 中自定义我的新按钮时遇到问题

I have a problem when I want to customize my new button in Kotlin

当我在 Kotlin 中创建 myButton 时,我的代码中出现了这个错误。

Button 是一个函数,而不是 class 扩展。只需在 MainActivity

中创建一个函数

例如

    class MainActivity : AppCompatActivity(){
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        MyButton()  // this is how to make button inside function

    }

    private fun MyButton(){

     // you can put your button listener here
     // example :

     mMyBtn.setOnClickListener {
            // and then put ur logic here
            Toast.makeText(this, "Button Clicked", Toast.LENGTH_SHORT).show()
        }

    }
}

或者尝试以下

class MyButton : androidx.appcompat.widget.AppCompatButton {
    constructor(context: Context?) : super(context!!)
    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs)
    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(context!!, attrs, defStyle)

    protected override fun onDraw(canvasObject: Canvas) {
        super.onDraw(canvasObject)
    }
}

让我知道这是否适合你:)

首先是警告,不是错误。您的代码仍然 运行 没问题。但是这个 warning/suggestion 的原因是因为 AppCompatButtonandroidx 库的一部分,它还提供了对某些功能的向后支持,它们也具有色调意识,这意味着它允许动态和背景色调。

来自 AppCompatButton

的文档

A Button which supports compatible features on older versions of the platform, >including:

  • Allows dynamic tint of its background via the background tint methods in ViewCompat.
  • Allows setting of the background tint using R.attr.backgroundTint and R.attr.backgroundTintMode.
  • Allows setting of the font family using R.attr.fontFamily.
  • This will automatically be used when you use Button in your layouts and the top-level activity / dialog is provided by appcompat. You should only need to manually use this class when writing custom views.

从上面开始,当您使用 Button 时,它会自动使用 AppCompatButton,因此您应该注意在自定义视图中扩展 AppCompatButton 以获取大部分内容。