0

I want to know, How can I write code without activity casting like a fragment?....

--------- A Fragment

        tempMainImage.setOnClickListener {
            val message = "how are you today"

            (activity as? MainActivity).let {
                it?.onReplaceTtsFragment(message)
            }
        }

---------- MainActivity

fun onCloseTtsFragmentLayout() {
        detailFragmentLayout.visibility = View.GONE
    }

    fun onReplaceTtsFragment(message: String) {
        supportFragmentManager.beginTransaction().replace(R.id.detailFragmentLayout, TtsDetailFragment.newInstance(message, ::onCloseTtsFragmentLayout)).commit()

        detailFragmentLayout.visibility = View.VISIBLE
    }
Ajay K S
  • 350
  • 1
  • 5
  • 16
soyLen
  • 1
  • Instead of casting activity `(getActivity())` you can either use interface or event bus to replace another fragment from fragment refer this answer https://stackoverflow.com/a/15007656/10097275 – nik Jan 20 '20 at 05:13
  • 4
    why do you _not_ want to cast ? – a_local_nobody Jan 20 '20 at 05:15
  • well, casting doesn't have problem. but I just wanted to try to use lambda interface :) – soyLen Jan 27 '20 at 06:36

2 Answers2

0

why not try using when block and the is keyword.

tempMainImage.setOnClickListener {
    val message = "how are you today"

    when (activity) {
        is MainActivity -> activity.onReplaceTtsFragment(message)
        else -> return
    }
Ryan
  • 948
  • 6
  • 20
0

is is the kotlin replacement for instanceof in java


tempMainImage.setOnClickListener {
    val message = "how are you today"

    if(activity is MainActivity) {
        activity?.onReplaceTtsFragment(message)
    }
}
Pavan Varma
  • 1,199
  • 1
  • 9
  • 21