gpt4 book ai didi

android - DialogFragment 监听器

转载 作者:行者123 更新时间:2023-12-02 13:10:46 29 4
gpt4 key购买 nike

我有一个带有监听器的 DialogFragment,用于单击按钮以调用 fragment 中的函数。
我收到 lateinit property listener has not been initialized当我单击肯定按钮时。
对话 fragment

class CreateCollectionDialog: DialogFragment() {
lateinit var listener: CreateCollectionDialogListener

interface CreateCollectionDialogListener {
fun onDialogPositiveClick(dialog: DialogFragment, collectionName: String)
// fun onDialogNegativeClick(dialog: DialogFragment)
}

override fun onAttachFragment(childFragment: Fragment) {
println("onAttachFragment")
super.onAttachFragment(childFragment)
listener = context as CreateCollectionDialogListener
println(listener)
}

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val builder = AlertDialog.Builder(it)
val inflater = requireActivity().layoutInflater
builder.setView(inflater.inflate(R.layout.dialog_collection, null))
.setPositiveButton("Create", DialogInterface.OnClickListener { dialog, id ->
// Create new collection
var newCollectionName = view?.findViewById<EditText>(R.id.newCollectionName)?.text.toString()
if (!newCollectionName.equals("") && newCollectionName != null) {
listener.onDialogPositiveClick(this, newCollectionName)
}
})
.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, id ->
// User canceled dialog
// listener.onDialogNegativeClick(this)
})
builder.create()
}?: throw IllegalStateException("Activity cannot be null")
}

override fun onStart() {
super.onStart()
val positive: Button = (dialog as AlertDialog?)!!.getButton(AlertDialog.BUTTON_POSITIVE)
positive.setTextColor(resources.getColor(R.color.topColor))

val negative: Button = (dialog as AlertDialog?)!!.getButton(AlertDialog.BUTTON_NEGATIVE)
negative.setTextColor(Color.RED)
}
}
fragment
class CollectionsFragment: Fragment(), CreateCollectionDialog.CreateCollectionDialogListener {
override fun onOptionsItemSelected(item: MenuItem): Boolean {

when (item.itemId) {
R.id.add -> {
val createDialog = CreateCollectionDialog()
createDialog.show(fragmentManager!!, "")
return true
}
}
return false
}

override fun onDialogPositiveClick(dialog: DialogFragment, collectionName: String) {
addNewCollection(collectionName)
}
}

最佳答案

onAttachFragment当一个 fragment 作为该 fragment 的子项附加时调用,在这种情况下,从不也不需要。
使用onAttach(Context context)对于当前情况。对话框 fragment 没有 child 所以onAttachFragment永远不会被调用。
要从父 fragment 初始化监听器,请使用:

// inside fragment lifecycle methods like onviewcreated etc
listener = getParentFragment() as CreateCollectionDialogListener

关于android - DialogFragment 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63001401/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com