我不能使用 findViewById(int)。无法参考



我只需要能够使用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)

您不能在活动之外访问布局的元素,或者没有对填充布局的活动的引用。您可以在应用程序的某个地方定义一个常数值:

object Constants{
var checked = false
}

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

if(Constants.checked){
databaseReference.child("c").setValue("C")
}
编辑,感谢用户十四号提醒我:

当你有一个对布局根视图的引用时,你也可以访问视图的元素。

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

最新更新