问题描述
我已经阅读了几个类似的问题,但我无法做出任何答案。关键在于
val popupMenu = findViewById<RecyclerView>(R.id.popmenu)
总是返回空值。
这里是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>
这是设置弹出窗口的代码:
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)
我做错了什么?
解决方法
您可能正在 Activity 中运行此代码,findViewById()
在 Activity 的视图层次结构中查找视图。您应该搜索膨胀视图的层次结构
val popupMenu = popupView.findViewById<RecyclerView>(R.id.popmenu)
,
我做错了什么?
您正在尝试在 current 视图层次结构中查找视图。您需要查看PopupWindow 的层次结构。
// 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)
修复:
将最后一行更改为 popupView.findViewById<RecyclerView>(r.id.popmenu)
,以便您在正确的视图层次结构中进行搜索。