HelloCW
HelloCW

Reputation: 2325

How can I add a function extension for Fragment class in Kotlin?

At present, I use Code B to display a message in a Fragment class, it works well.

I hope to use Code A to do it, so I write Code C, but Code C is wrong, how can I fix Code C ? Thanks!

Code A

import org.jetbrains.anko.*
class UIFragmentCamera : Fragment() {
   private fun updateCameraUi() {
       toast("Hello")
    }
}

Code B

import org.jetbrains.anko.*
class UIFragmentCamera : Fragment() {
   private fun updateCameraUi() {
        requireContext().toast("Hello")
    }
}

Code C

fun Fragment.toast(info:String) {
    requireActivity().toast(info)
}

Upvotes: 2

Views: 3392

Answers (3)

Raghul Vaikundam
Raghul Vaikundam

Reputation: 588

Make sure you imported androidx.fragment.app.Fragment or android.app.Fragment in the extension function defined file

requireActivity returns FragmentActivity whereas requireContext returns Context. I believe your toast is another extension function which display message based on the type Context

Code C

fun Context.toast(message: String) {
    Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}

fun Fragment.toast(info: String) {
    requireContext().toast(info)
}

Upvotes: 7

Vinayakkumar
Vinayakkumar

Reputation: 6520

import android.widget.Toast
import androidx.fragment.app.Fragment


fun Fragment.toast(message :String ){
    Toast.makeText(requireContext(),message,Toast.LENGTH_SHORT).show()
}

Upvotes: 0

Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 15433

Option - 1: If you want to create extension function of Fragment class you have to do it in this way

fun Fragment.toast(message: String) {
    Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
}

And from inside fragment you can call this like below:

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

    //Here it is 
    toast("Hello")

    return super.onCreateView(inflater, container, savedInstanceState)
}

Option - 2: You can create extension function for Context class like this

fun Context.toast(message: String) {
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

Then you can call this from Fragment like below:

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

    //Here it is, both are valid
    requireActivity().toast("Hello")
    requireContext().toast("World")

    return super.onCreateView(inflater, container, savedInstanceState)
}

You can also call this from Activity like below:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    toast("Hello World")

}

Upvotes: 2

Related Questions