【问题标题】:How to invoke DialogFragment from function which is out of activity and fragment in Android?如何从Android中没有活动和片段的函数调用DialogFragment?
【发布时间】:2020-09-25 12:02:22
【问题描述】:

我有一个名为 DialogDialogFragment。如何从 Android 中没有活动和片段的函数调用它?

这是DialogFragment

class Dialog: DialogFragment() {

    private var array = arrayOf("Yes", "No")
    var a = ""
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.activity_main, container)
        val myListView = rootView.findViewById(R.id.listview_1) as ListView
        myListView.adapter = ArrayAdapter(context!!, R.layout.list_item, array)
        myListView.setItemChecked(0,true)
        val okbutton = rootView.findViewById<Button>(R.id.ok)
        var cancelbutton = rootView.findViewById<Button>(R.id.cancel)
        var title = rootView.findViewById<TextView>(R.id.title)
        title.text="Choose one option"
        cancelbutton.setOnClickListener { dismiss() }
        okbutton.setOnClickListener {
            Toast.makeText(context, "OK", Toast.LENGTH_LONG).show()
        }
        myListView.setOnItemClickListener { adapterView,
                                            view,
                                            position,
                                            l
            ->
            Toast.makeText(context, "${array[position]}", Toast.LENGTH_LONG).show()
        }
        return rootView
    }
}

这是我想从那里调用 Dialog 的函数:

private val fm = supportFragmentManager

fun TestFunction() {
    Dialog().show(fm, "")
}

但是supportFragmentManager是红色的,在函数中无法识别。

【问题讨论】:

  • 那么通过参数发送片段管理器呢?
  • 怎么样?请发送答案
  • 我认为您不能在片段或活动之外显示对话框。

标签: android function android-studio dialogfragment


【解决方案1】:

supportFragmentManagerActivityfragment 类中的变量,因此您不能在没有在 Activity 类或片段中的情况下使用

  • 如果您想对其进行测试,请使用 Espresso 测试 UI
  • 如果您在业务层使用它,它将违反干净的代码,因此请使接口包含在 Activity 中实现的显示功能或在逻辑完成时调用的业务类中的片段
  • 如果您坚持让它成为业务,请传递一个上下文并将其转换为您的 Activity 类

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 2013-10-28
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多