I have and simple app form (Android dev course) and I learn to use RecyclerView. The code works fine (if I use RecyclerView in MainActivity) but if I want to put that RecyclerView inside a PopupWindow, the app crashes (in most of my attempts: The specified child already has a parent
, and I can't use removeView()
).
So how can I use the RecyclerView inside PopupWindow?
This is ItemAdapter:
class ItemAdapter(
private val context: Context,
private val dataset: List<Affirmation>
) : RecyclerView.Adapter<ItemAdapter.ItemViewHolder>() {
class ItemViewHolder(private val view: View) : RecyclerView.ViewHolder(view) {
val textView: TextView = view.findViewById(R.id.item_title)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val adapterLayout = LayoutInflater.from(parent.context)
.inflate(R.layout.list_item, parent, false)
return ItemViewHolder(adapterLayout)
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val item = dataset[position]
holder.textView.text = context.resources.getString(item.stringResourceId)
}
override fun getItemCount(): Int {
return dataset.size
}
}
This is MainActivity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val myDataset = Datasource().loadAffirmations()
val btn = findViewById<Button>(R.id.button)
btn.setOnClickListener {
val popup_window = PopupWindow(this)
val inflator = layoutInflater.inflate(R.layout.popup_list, null)
popup_window.contentView = ???
popup_window.showAsDropDown(btn)
}}}
This is popup_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recycler_view"
app:layoutManager="LinearLayoutManager"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
list_item.xml
is a simple TextView
and in activity_main.xml
I have just a Button for open the PopupWindow
Update this and you should see a pop window below button.
popup_window.contentView = inflator.rootView
After that it logcat will print No adapter attached; skipping layout
thats where you initiate your reyclerview and adapter and attach the adapter to your recyclerview inside popup_list.
I am not going to be in very detail as this answer is very well asked and answered Here.