【发布时间】:2018-04-10 14:20:35
【问题描述】:
我有一个处理 RecyclerView 的 MainAdapter.kt 类。在其 Holder 类中,我使用 OnLongClickListener 调用函数 deleteCategory(categoryId) 来删除我的 Firebase 数据库中的条目。这完美地工作:
class CategoryHolder(val customView: View, var category: Category? = null) : RecyclerView.ViewHolder(customView) {
private val TAG = CategoryHolder::class.java.simpleName
fun bind(category: Category) {
with(category) {
customView.textView_name?.text = category.name
customView.textView_description?.text = category.description
val categoryId = category.id
customView.setOnClickListener {
// do something
}
customView.setOnLongClickListener(
{
deleteCategory(categoryId)
true
}
)
}
}
private fun deleteCategory(categoryId: String) {
val database = FirebaseDatabase.getInstance()
val myRef = database.getReference("categories").child(categoryId)
myRef.removeValue()
Log.d(TAG, "Category with id " + categoryId + " deleted")
}
}
但我宁愿调用 DialogFragment 类中的函数而不是 deleteCategory(id) 函数,如下所示:
// Create an instance of a DeleteCategoryDialogFragment and show it
fun showDeleteCategoryDialog(view: View, categoryId: String) {
val dialog = DeleteCategoryDialogFragment.newInstance(categoryId)
dialog.show(this@MainActivity.supportFragmentManager,
"DeleteCategoryDialog")
}
这给了我一个“未解决的引用:@MainActivity”错误。 我该如何解决这个问题?有没有办法在我的 MainActivity 中获取 categoryId(字符串类型)?这将允许我将函数 showDeleteCategoryDialog 移动到 MainActivity 并解决问题。
【问题讨论】:
-
你在哪里定义
showDeleteCategoryDialog()函数?在适配器内部? -
是的,因为我需要为 categoryId 提供一个值,这是我在 CategoryHolder 的绑定函数中检索到的字符串。 showDeleteCategoryDialog() 函数在 MainActivity 中定义并提供“假” categoryId 时工作正常。
标签: android firebase kotlin adapter dialogfragment