首页 > 解决方案 > 在对话框中填充 RecyclerView

问题描述

我找到了一个解决方案并将其作为答案附加

我目前在使用来自我的适配器的信息的对话框中填充布局时遇到问题。数据是从 API 获取并传递到我的数据类中,但由于我试图引用的 recyclerview 在对话框的布局文件中,而不是在我用来调用所述对话框的文件中,因此视图只返回一个 null .

这是我的上下文代码。

CheckboxActivity.kt(只是回调)people_list 返回 null

private val callbackGETUSERS = object : Callback<List<Users>> {
    override fun onFailure(call: Call<List<Users>>, t: Throwable) {
        Log.e("API-GET-USERS", "Problem GETTING USERS", t)        }

    override fun onResponse(call: Call<List<Users>>, response: Response<List<Users>>) {

        val result = UsersResult(response.body() ?: return run {
            Log.e("API-ME", "Problem calling USERS")
        })

        peopleList = result
        people_list.adapter = ManagePeopleAdapter(result)
    }

}

d_manage_people.xml(对话资源文件)

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="16dp">

<TextView
        android:id="@+id/manage_people_title"
        android:gravity="center"
        android:height="24dp"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        style="@style/Subtitle1"
        android:text="Create Item"
        android:layout_marginBottom="16dp"
        android:layout_gravity="center"/>

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/people_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

</androidx.recyclerview.widget.RecyclerView>

这是我的错误

java.lang.IllegalStateException: people_list must not be null

顺便说一句,我使用的插件允许我不使用 findViewById

任何帮助,将不胜感激 :)

标签: androidkotlinandroid-recyclerviewdialogadapter

解决方案


您可以在 API 调用后显示对话框。像下面的东西

private val callbackGETUSERS = object : Callback<List<Users>> {
    override fun onFailure(call: Call<List<Users>>, t: Throwable) {
        Log.e("API-GET-USERS", "Problem GETTING USERS", t)        }

    override fun onResponse(call: Call<List<Users>>, response: Response<List<Users>>) {
        val result = UsersResult(response.body() ?: return run {
            Log.e("API-ME", "Problem calling USERS")
        })
        peopleList = result
        this@CheckboxActivity.showDialog()
    }
}

private fun showDialog() {
    val dialog = AlertDialog.Builder(this)
    val view = layoutInflater.inflate(R.layout.d_manage_people, null)
    view.manage_people_title.text = "Manage People" 
    people_list = view.findById(R.id.people_list)
    people_list.adapter = ManagePeopleAdapter(peopleList)
    dialog.setView(view)
    dialog.show() }
}

只需在单击按钮时调用 API。

onPeopleClicked(view: View) {
    dataRetriever.getUsers(callbackGETUSERS, getAuth(), listID)
}

推荐阅读