[英]I have a problem when I want to customize my new button in Kotlin
I have this error in my code when I create myButton
in Kotlin.当我在 Kotlin 中创建myButton
时,我的代码中有此错误。
Button
is a Function, not a class extended. Button
是 Function,而不是 class 扩展。 Just make an function in MainActivity
只需在MainActivity
中创建一个 function
For example例如
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()
}
}
}
or maybe try below或者试试下面
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)
}
}
let me know if this works for you:)让我知道这是否适合你:)
Firstly it a warning, not an error.首先它是一个警告,而不是一个错误。 Your code will still run fine.您的代码仍然可以正常运行。 But the reason for this warning/suggestion is because AppCompatButton
is part of androidx
library also comes with backward support for some features, they are also tint aware meaning it allows dynamic and background tints.但是这个警告/建议的原因是因为AppCompatButton
是androidx
库的一部分,还提供了对某些功能的向后支持,它们也具有色调意识,这意味着它允许动态和背景色调。
From the documentation of AppCompatButton来自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.允许通过 ViewCompat 中的背景着色方法对其背景进行动态着色。
- Allows setting of the background tint using R.attr.backgroundTint and R.attr.backgroundTintMode.允许使用 R.attr.backgroundTint 和 R.attr.backgroundTintMode 设置背景色调。
- Allows setting of the font family using R.attr.fontFamily.允许使用 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.当您在布局中使用 Button 并且顶级活动/对话框由 appcompat 提供时,这将自动使用。 You should only need to manually use this class when writing custom views.您应该只需要在编写自定义视图时手动使用此 class。
From above, When ever you use a Button
, it automatically uses AppCompatButton
, so you should take care of extending AppCompatButton
in custom views to get most of it.从上面看,当您使用Button
时,它会自动使用AppCompatButton
,因此您应该注意在自定义视图中扩展AppCompatButton
以充分利用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.