简体   繁体   中英

How to make SnackBar in Android Fragment?

How to make SnackBar in Android Fragment?

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.

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

and Snackbar

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.

 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.

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. It seems to be android.R.id.content is in different layout compared to activity_main. 在此处输入图像描述

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. This way works correctly like the way we always thought. 在此处输入图像描述

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