[英]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.我的代码中没有错误,但是在尝试声明 toast 小部件时出现错误。 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:选项1:
Toast.makeText(context!!, "saving", Toast.LENGTH_SHORT).show()
The !!
的
!!
(not-null assertion operator) is used to denote the variable is not null. (非空断言运算符)用于表示变量不是 null。
Option 2:选项 2:
Using let and safe calls使用 let 和 safe 调用
context?.let{ context->
Toast.makeText(context, "saving", Toast.LENGTH_SHORT).show()
}
Refer: https://kotlinlang.org/docs/reference/null-safety.html for more details参考: https://kotlinlang.org/docs/reference/null-safety.html了解更多详情
Toast.makeText(activity,message,Toast.LENGTH_LONG).show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.