如何解决如何让 RecyclerView 在 Android PopupWindow 中工作?
我已经阅读了几个类似的问题,但我无法做出任何答案。关键在于
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)
,以便您在正确的视图层次结构中进行搜索。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。