CEO*_*pps 0 android adapter kotlin firebase dialogfragment
我有一个MainAdapter.kt类来处理RecyclerView.在其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")
}
}
Run Code Online (Sandbox Code Playgroud)
但我宁愿调用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")
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个"未解决的参考:@MainActivity"错误.我怎么解决这个问题?有没有办法在我的MainActivity中获取categoryId(String类型)?这将允许我将函数showDeleteCategoryDialog移动到MainActivity并解决问题.
你不能MainActivity在上面提到你的代码.你必须投出context您的ViewHolder是MainActivity使用它之前:
val activity = itemView.context as? MainActivity
// then you can show your dialog with activity?.supportFragmentManager
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1903 次 |
| 最近记录: |