如何从Fragment调用FragmentManager?科特林

时间:2019-03-24 19:20:38

标签: android kotlin

我正在构建警报应用程序,并尝试打开时间选择器对话框。关闭后,我需要获取时间数据。问题出在.show()函数中。它不能分段工作。它说None of the following functions can be called with the arguments supplied.

我的课

class AlarmPickerDialog : DialogFragment() {
    override fun onCreateView(inflater: LayoutInflater?, container:
    ViewGroup?, savedInstanceState: Bundle?): View {

        var myView = inflater!!.inflate(R.layout.alarm_time_picker, container, false)

        return myView
    }
}

我的调用方法

val alarmDialog = AlarmPickerDialog()
val fm = getActivity()!!.getSupportFragmentManager()
alarmDialog.show(fm, "MyDialog")

也许有更好的方法来获取时间数据?

3 个答案:

答案 0 :(得分:2)

问题:似乎AlarmPickerDialogandroid.app.DialogFragment而不是android.support.v4.app.DialogFragment扩展过来。

解决方案::将代码更改为

// Comment-out this line
// import android.app.DialogFragment

// Add this line
import android.support.v4.app.DialogFragment

class AlarmPickerDialog : DialogFragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        var myView = inflater!!.inflate(R.layout.alarm_time_picker, container, false)
        return myView
    }
}

答案 1 :(得分:0)

嘿,请尝试执行以下步骤, https://developer.android.com/reference/android/app/DialogFragment您的问题说明了如何调用片段管理器,但是您已经调用了它, 这就是为什么您的问题不能这么解决问题并尝试遵循此文档可能会有所帮助的原因。

答案 2 :(得分:0)

以下是您的代码的解决方案:

DialogFragment的代码

class ListFragment: DialogFragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val rootView = inflater.inflate(R.layout.list_layout, container)
        var pioneers = arrayOf("Jon Snow", "Mother of Dragon-Khalessi", "Ned Stark", "Benjen Stark", "Cathlyen Stark", "Arya Stark", "Sansa Stark", "Littelfiger", "Jamie Lannister")

        val myListView = rootView.findViewById(R.id.myListView) as ListView
        myListView!!.adapter = ArrayAdapter<String>(activity, android.R.layout.simple_list_item_1, pioneers)

        this.dialog.setTitle("Game Of Thrones")

        myListView.setOnItemClickListener {
            adapterView,
            view,
            position,
            l
            -> Toast.makeText(activity, pioneers[position], Toast.LENGTH_SHORT).show()
        }

        return rootView
    }
}


In your activity you can make call something like this

val openFragmentBtn = findViewById<Button>(R.id.openFragmentID)

//On button Click Open Dialog Fragment
    val openFragmentBtn = findViewById(R.id.openFragmentID) as Button

            val fm = supportFragmentManager
            val listFragment= ListFragment()

            openFragmentBtn.setOnClickListener(object : View.OnClickListener {
                override fun onClick(view: View) {
                    listFragment.show(fm, "PioneersFragment_tag")
                }
            })

尝试一下

val pop = alarm_first()
val fm = this@YourActivityName.fragmentManager
pop.show(fm, "name")

我已出于学习目的实现了此代码,但如果对您有用,我很乐意提供帮助