-1

I have a DialogFragment which name is Dialog. How can I invoke it from a function which is out of activity and fragment in Android?

This is the 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
    }
}

And this is function which I want to invoke Dialog from there:

private val fm = supportFragmentManager

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

But supportFragmentManager is in red and is not recognized in the function.

MMG
  • 3,226
  • 5
  • 16
  • 43

1 Answers1

0

supportFragmentManager is variable in Activity or fragment class so you can not use without being in Activity class or fragment

  • if you want to test it use Espresso for test UI
  • if you use it in the business layer it will be against clean code so please make interface contain show function that implemented in Activity or fragment in business class that invoked when logic has done
  • if you insist to make it business so please pass a context and cast it to your Activity class
Shalu T D
  • 3,921
  • 2
  • 26
  • 37
ahmed shaaban
  • 116
  • 1
  • 3