supportFragmentManager无法与Kotlin一起使用 [英] supportFragmentManager not working with kotlin

查看:79
本文介绍了supportFragmentManager无法与Kotlin一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用使用kotlin的AlertDialog类创建自定义对话框,这是我的方法首先是对话框的类

I'm trying to make a custom dialog using AlertDialog class using kotlin and there is how I do it first here the class for the dialog

class CreateDialogForProduct : AppCompatDialogFragment() {
    lateinit var nameET: EditText
    lateinit var barcodeET: EditText
    lateinit var detailsET: EditText
    lateinit var saveBtn: Button


    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        var builder = AlertDialog.Builder(activity)
        val inflater = layoutInflater
        var view = inflater.inflate(R.layout.layout_dailog,null)
        builder.setView(view)
        builder.setTitle("Save Product")
        builder.setCancelable(true)

        nameET = view.findViewById(R.id.name_tv)
        barcodeET = view.findViewById(R.id.barcode_tv)
        detailsET = view.findViewById(R.id.details_tv)
        saveBtn = view.findViewById(R.id.save_btn)

        return builder.create()
    }
}

这就是我面对问题的活动中的称呼方式

and here is how I call it in the activity where the I faced the problem

fun openDialog(){

    val dialog = CreateDialogForProduct()
    dialog?.show(supportFragmentManager, null)

}

它给我一个错误,没有像supportFragmentManger这样的方法,我检查了这个 answer 但是它的解决方案对我不起作用,有帮助吗?

it gives me an error there is no method like supportFragmentManger, and I checked this answer but it's solution didn't work with me, anyhelp?

推荐答案

如果需要,您可以从AppCompatActivity扩展活动,这不是问题,但可以声明这样的方法,它将为您服务

You can extend your activity from AppCompatActivity if you want, it isn't your problem but declare the method like that and it will work for you

fun openDialog(){
    val dialog = CreateDialogForProduct()
    dialog.show((activity as FragmentActivity).supportFragmentManager, null)

}

完整的活动课将是这样

lateinit var fab: FloatingActionButton
lateinit var activity:Activity
var onClickListener = View.OnClickListener() {
    when (it.getId()) {
        R.id.floatingActionButton -> openDialog()
    }
}

fun openDialog(){
    val dialog = CreateDialogForProduct()
    dialog.show((activity as FragmentActivity).supportFragmentManager, null)

}
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        activity = this

        fab = findViewById(R.id.floatingActionButton)
        fab.setOnClickListener(onClickListener)
    }

}

这篇关于supportFragmentManager无法与Kotlin一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆