我有这些View
函数扩展:
fun View.showSnackbar(msgId: Int, length: Int) {
showSnackbar(context.getString(msgId), length)
}
fun View.showSnackbar(msg: String, length: Int) {
showSnackbar(msg, length, null, {})
}
fun View.showSnackbar(
msgId: Int,
length: Int,
actionMessageId: Int,
action: (View) -> Unit
) {
showSnackbar(context.getString(msgId), length, context.getString(actionMessageId), action)
}
fun View.showSnackbar(
msg: String,
length: Int,
actionMessage: CharSequence?,
action: (View) -> Unit
) {
val snackbar = Snackbar.make(this, msg, length)
if (actionMessage != null) {
snackbar.setAction(actionMessage) {
action(this)
}.show()
}
}
我试图在我的片段中使用它,但Snackbar
不显示。它没有崩溃,只是没有显示出来。但是,我的showSnackbar2()
工作。以下是我在片段中使用它的方式:
class AddressesFragment : Fragment() {
private lateinit var binding: FragmentAddressesBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentAddressesBinding.inflate(inflater, container, false)
binding.buttonSnackbar.setOnClickListener {view ->
//showSnackbar1() // DOES NOT WORK!!
showSnackbar2()
}
return binding.root
}
fun showSnackbar1() {
binding.buttonSnackbar.showSnackbar(
R.string.location_permission_granted,
Snackbar.LENGTH_SHORT
)
}
fun showSnackbar2() {
val view = activity?.findViewById(android.R.id.content) as View
Snackbar.make(
view,
R.string.location_permission_granted,
Snackbar.LENGTH_SHORT
).show()
}
}
如何修复我的函数扩展,使showSnackbar1()
工作?
2条答案
按热度按时间vc6uscn91#
您的
Snackbar
未显示,因为您正在检查if (actionMessage != null)
。如果actionMessage == null
,则不会显示Snackbar
。请查看下面的详细说明:因此,您需要在最后一个方法中传递action message,以显示您的
Snackbar
。42fyovps2#
此扩展功能起作用。它扩展View对象并调用Snackbar对象:
然后按如下方式使用: