rag*_*oat 3 android kotlin dialogfragment
我有一个 DialogFragment,其中有一个侦听器,用于监听单击按钮以调用片段中的函数时的情况。
lateinit property listener has not been initialized
当我点击肯定按钮时,我得到了。
对话框片段
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)
}
}
Run Code Online (Sandbox Code Playgroud)
分段
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)
}
}
Run Code Online (Sandbox Code Playgroud)
onAttachFragment
当一个片段作为该片段的子片段附加时调用,在这种情况下,从不也不需要。
对当前场景使用onAttach(Context context) 。对话框片段没有子级,因此onAttachFragment
永远不会被调用。
要从父片段初始化侦听器,请使用:
// inside fragment lifecycle methods like onviewcreated etc
listener = getParentFragment() as CreateCollectionDialogListener
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1552 次 |
最近记录: |