【发布时间】: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 没有这个。