I am trying to display a custom toast view in my app when the user receives a notification. The custom toast appears fine, but I can't inflate its content and then update it as I wish. Here is my code:
Watcher class receiving the notification
class Watcher : ParsePushBroadcastReceiver() {
override fun onPushReceive(context: Context, intent: Intent) {
NotificationToast.show(context, "title text")
}
}
NotificationToast.kt
class NotificationToast {
companion object {
fun show(context: Context, title: String) {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val layout = inflater.inflate(R.layout.notification_toast, null)
// This line below always returns null
layout.findViewById<AppCompatTextView>(R.id.notification_toast_title_text_view).text = title
val toast = Toast(context)
toast.duration = Toast.LENGTH_SHORT
toast.setGravity(Gravity.TOP, 0, 0)
toast.view = layout
toast.show()
}
}
}
notification_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/notification_toast"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginHorizontal="24dp"
android:layout_marginTop="24dp" >
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/notification_toast_title_text_view"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_margin="16dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
For some reason, in NotificationToast, the line with the findViewById()
trying to access the notification_toast_title_text_view
textview is always null. What is the reason?
Thank you for your help