I have read several similar questions but I couldn't make any of the answers work. The sticking point is that
val popupMenu = findViewById<RecyclerView>(R.id.popmenu)
always returns null.
Here is activity_popup.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/popupactivity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PopupActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/popmenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the code to set up the PopupWindow:
val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val popupView = inflater.inflate(R.layout.activity_popup, null)
popupWin = PopupWindow(popupView, popupWidth, popupHeight, true)
val layoutMgr = LinearLayoutManager(applicationContext)
val popupMenu = findViewById<RecyclerView>(R.id.popmenu)
What am I doing wrong?
What am I doing wrong?
You're trying to find a view in the current view hierachy. You need to be looking in the PopupWindow's hierarchy.
// Inflates a layout that's not attached to anything
val popupView = inflater.inflate(R.layout.activity_popup, null)
// Creates a PopupWinow with the given popupView that's not attached to anything
popupWin = PopupWindow(popupView, popupWidth, popupHeight, true)
val layoutMgr = LinearLayoutManager(applicationContext)
// Attempts to find the recycler view in *this* view hierchy, which does not exist
val popupMenu = findViewById<RecyclerView>(R.id.popmenu)
To Fix:
Change the last line to popupView.findViewById<RecyclerView>(r.id.popmenu)
so you're searching within the correct view hierarchy.