首页 > 解决方案 > Android Studio 初学者问题:为什么我不能从 Button 属性窗口中选择正确的 onClick 函数?

问题描述

我试图让我的按钮向手机发送通知,所以我在 MainActivity.kt 类中创建了一个函数sendNotification

这是我放入函数的 Android Docs 中的代码:

fun sendNotification(view: View){
    with(NotificationManagerCompat.from(this)) {
        notify(notificationId, mBuilder.build())
    }
}

如果它以某种方式有帮助,这是代码的其余部分:

val notificationId = 1
val channel_id = "channel"

fun createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = getString(R.string.channel_name)
        val descriptionText = getString(R.string.channel_description)
        val importance = NotificationManager.IMPORTANCE_DEFAULT

        val channel = NotificationChannel(channel_id, name, importance).apply {
            description = descriptionText
        }
        // Register the channel with the system
        val notificationManager: NotificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
}

var mBuilder = NotificationCompat.Builder(this, channel_id)
    .setSmallIcon(R.drawable.ic_launcher_foreground)
    .setContentTitle("Hello from my first notification!")
    .setContentText("Aayyee wassup?")
    .setStyle(NotificationCompat.BigTextStyle().bigText("Aayyee wassup this is some longer text..."))
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)

现在,当我尝试在 activity_main.xml 中设置 onClick 属性时,我得到 了这个。当我单击带有 [MainActivity] 的 sendNotification 功能时,它只是切换到上面的那个。运行应用程序时,单击按钮时没有任何反应。

请原谅粗略的代码,因为我是初学者,并且大部分代码来自 Android Docs。如果需要,请询问更多信息。任何帮助表示赞赏。谢谢 :)

标签: androidandroid-studiouser-interfacebuttonkotlin

解决方案


推荐阅读