我正在 Kotlin 中的 Click listener 上实现,但它不起作用。当我单击按钮时,没有任何 react 。下面是代码:
class MainActivity : AppCompatActivity(), View.OnClickListener{
var area: MaterialButton? = null; var length: MaterialButton? = null
var time: MaterialButton? = null;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
area = findViewById(R.id.button_area)
length = findViewById(R.id.button_length)
time = findViewById(R.id.button_time)
setClickListeners()
}
private fun setClickListeners() {
area?.setOnClickListener(this)
length?.setOnClickListener(this)
time?.setOnClickListener(this)
}
fun toggleDrawer(view: View) {
showToast("Drawer")
}
fun openSettings(view: View) {}
override fun onClick(v: View) {
when (v.id) {
R.id.button_area, R.id.button_length,
R.id.button_time -> showToast("Click")
else ->{
showToast("Drawer")
}
}
}
private fun showToast(str: String){
Toast.makeText(this,str,Toast.LENGTH_LONG).show()
}
}
XML onClick 属性不起作用。<include
layout="@layout/toolbar_content"/>
我在主要 Activity (xml)中包含了包含属性的布局。包含的 View onClick 方法是:fun toggleDrawer(view: View) {
showToast("Drawer")
}
fun openSettings(view: View) {}
他们不工作。事实上我得到了错误。在 id 为“drawer_icon”的 View 类 com.google.android.material.button.MaterialButton 上的 onClick 处理程序的 Activity 类 android.view.ContextThemeWrapper 中找不到方法 toggleDrawer(View)。我已经在 MaterialButton 标签中声明了这些方法。这个按钮的布局是toolbar_content。如何解决所有这些问题。
最佳答案
如果要设置 onClick
到包含布局中的特定 View ,在 onCreate
中使用它:
// Apply click listener to one view in the included layout
val includedLayoutButton: View = findViewById<View>(R.id.includedLayout).findViewById(R.id.butInIncludedLayout)
includedLayoutButton.setOnClickListener {
Log.d("in", "on click")
}
主要的.xml<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="@+id/includedLayout"
layout="@layout/layout_test" />
</androidx.constraintlayout.widget.ConstraintLayout>
布局测试.xml<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/butInIncludedLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</FrameLayout>
关于android - 关于 Click 实现在 Kotlin 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63085089/