【问题标题】:I can't use findViewById(int). Reference is not possible我不能使用 findViewById(int)。无法参考
【发布时间】:2021-10-05 02:51:01
【问题描述】:

我只需要能够使用 findViewById(int)。我看过几个例子。但我无法理解它,因为它与我有点不同。

我需要知道通知中复选框的真实值,为此我必须使用 findViewById(int)。 请帮助我如何修复代码,以便我可以引用复选框。

该错误仅发生在 findViewById(int) 中。

代码如下:

companion object {
    const val NOTIFICATION_ID = 100
    const val NOTIFICATION_CHANNEL_ID = "1000"

}

override fun onReceive(context: Context, intent: Intent) {
    createNotificationChannel(context)
    notifyNotification(context)

}

private fun createNotificationChannel(context: Context) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val notificationChannel = NotificationChannel(
            NOTIFICATION_CHANNEL_ID,
            "기상 알람",
            NotificationManager.IMPORTANCE_HIGH
        )

        NotificationManagerCompat.from(context).createNotificationChannel(notificationChannel)


    }
}

private fun notifyNotification(context: Context) {

    with(NotificationManagerCompat.from(context)) {

        val build = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
            .setContentTitle("알람")
            .setContentText("일어날 시간입니다.")
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setPriority(NotificationCompat.PRIORITY_HIGH)


        notify(NOTIFICATION_ID, build.build())

        val firebaseDatabase = FirebaseDatabase.getInstance()
        val databaseReference = firebaseDatabase.reference

        val cb1 = findViewById<CheckBox>(R.id.checkBox)
        if (cb1.isChecked == true) {
            databaseReference.child("c").setValue("C")

        }
    }

 }

无法使用requireView

val cb = requireView().findViewById<CheckBox>(R.id.checkbox)

        if (cb.ischecked == true)

【问题讨论】:

  • 如果这是在 Fragment 而不是 Activity 中,请使用 requireView().findViewById…。您调用的函数用于在某个视图组中搜索视图。当你看到它在没有视图组的情况下被调用时,那是因为 Activity 类有一个快捷方式,可以让你直接调用该函数,它会自动为你在当前布局的根视图上调用它。 Fragment 没有这个。

标签: android kotlin


【解决方案1】:

您无法在 Activity 之外访问布局的元素,或者在没有引用使布局膨胀的 Activity 的情况下。您可以在应用程序的某处定义一个常量值:

object Constants{
  var checked = false
}

并在复选框的 onChecked 事件上更新它。然后您可以在通知代码中访问已检查的变量:

if(Constants.checked){
  databaseReference.child("c").setValue("C")
}

编辑,感谢用户tenfour提醒我:

当您引用布局的根视图时,您还可以访问视图的元素。

view.findViewById<CheckBox>(R.id.checkbox).isChecked

【讨论】:

  • 这是错误的。如果您有对布局根视图的引用,则可以访问布局的元素。
  • 我认为在广播中使用它是问题所在。无法使用 findViewById 将当前屏幕上的视图作为上下文获取。我们正在寻找一种将参数添加到创建通知并使用它的函数的方法。
  • 我已按照您的建议附上了我编码的内容。无法使用 requireView 或 view
  • 您是否尝试过使用带有布尔值的单例对象,就像我的第一个示例一样?这可能会奏效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
相关资源
最近更新 更多