简体   繁体   中英

How to Display a Toast Widget in A Fragment?

I am in an activity fragment whereby i want to display a toast widget after the commands for the submit button have been met and completed.

the code:

class HomeFragment : Fragment() {

private val currentUserDocRef = Firebase.firestore.collection("users")

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val view = inflater.inflate(R.layout.fragment_home, container, false)

    view.apply {

        submitbutton.setOnClickListener {
            FirestoreUtil.updateCurrentUser(
                edittextPersonname.text.toString(),
                editTextBio.text.toString(),
                editTextTextEmailAddress.text.toString(),
                edittextage.text.toString()

                )
        }

        return view
    }

}

no error is present in my code however on trying to declare a toast widget i get an error. code:

 Toast.makeText(this@HomeFragment, "saving", Toast.LENGTH_SHORT).show()

the error:

错误信息

You need a context to show toast, here is the code:

Toast.makeText(this@HomeFragment.requireActivity(), "saving", Toast.LENGTH_SHORT).show()

Thanks

The context should not be nullable type. The error shows that it is a type mismatch.

Option 1:

Toast.makeText(context!!, "saving", Toast.LENGTH_SHORT).show()

The !! (not-null assertion operator) is used to denote the variable is not null.

Option 2:

Using let and safe calls

context?.let{ context->
    Toast.makeText(context, "saving", Toast.LENGTH_SHORT).show()
}

Refer: https://kotlinlang.org/docs/reference/null-safety.html for more details

Toast.makeText(activity,message,Toast.LENGTH_LONG).show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM