简体   繁体   English

如何在 Android 片段中制作 SnackBar?

[英]How to make SnackBar in Android Fragment?

How to make SnackBar in Android Fragment?如何在 Android 片段中制作 SnackBar?

What context should i call for it?我应该在什么背景下要求它?

 override fun onTaskLongClick(task: Task) {        
        Snackbar.make(view!!.rootView, "Long Click removed...", Snackbar.LENGTH_LONG).show()
    }

this code is working anyway, but it covers the soft key.这段代码无论如何都可以工作,但它涵盖了软键。

You pass a View that is not a CoordinatorLayout the Snackbar will walk up the tree until it finds a CoordinatorLayout or the root of the layout.您传递一个不是CoordinatorLayout的 View, Snackbar将沿着树向上走,直到找到CoordinatorLayout或布局的根。

  rootlayout = (CoordinatorLayout) rootView.findViewById(R.id.coordinatorLayout);

and SnackbarSnackbar

Snackbar snackbar = Snackbar.make(rootlayout , "Snackbar test", Snackbar.LENGTH_SHORT);
                            View sbView = snackbar.getView();
                            TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
                            textView.setTextColor(Color.YELLOW);
                            snackbar.show(); 

Wrong way 1.方法不对 1。

 override fun onTaskLongClick(task: Task) {        
        Snackbar.make(view!!.rootView, "Long Click removed...", Snackbar.LENGTH_LONG).show()
    }

This code will cover the software button of phone.此代码将涵盖手机的软件按钮。 Totally not good at all.完全不好。 在此处输入图像描述

Wrong way 2.错误的方式2。

override fun onTaskLongClick(task: Task) {     
Snackbar.make(activity!!.findViewById(android.R.id.content), "Long Click removed..."
, Snackbar.LENGTH_LONG).show()
    }

This way seems to be working properly, but it covers the floating button and cannot be removed by user.这种方式似乎工作正常,但它覆盖了浮动按钮,用户无法移除。 This means user has to wait until SnackBar disappear.这意味着用户必须等到 SnackBar 消失。 It seems to be android.R.id.content is in different layout compared to activity_main.与 activity_main 相比,android.R.id.content 的布局似乎不同。 在此处输入图像描述

Right way!正确的路!

override fun onTaskLongClick(task: Task) {       
        Snackbar.make(activity!!.findViewById(R.id.activity_main), "Long Click removed...", Snackbar.LENGTH_LONG).show()
    }

Adding id to activity_main.xml layout and call layout by findviewbyid.将id添加到activity_main.xml布局并通过findviewbyid调用布局。 This way works correctly like the way we always thought.这种方式就像我们一直认为的那样正常工作。 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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