Snackbar is not working within fragment class

不打扰是莪最后的温柔 提交于 2019-11-28 21:02:12

You can also use:

getActivity().findViewById(android.R.id.content)

like this:

Snackbar snackBar = Snackbar.make(getActivity().findViewById(android.R.id.content),
           "Look at me, I'm a fancy snackbar", Snackbar.LENGTH_LONG);
snackBar.show();

See this

deepak

I have solved this:

It is fine if we do not include CoordinatedLayout to my fragment_home.xml

Solution:

Defined : private RelativeLayout mRoot;

Now initialize in initUI(View view)

mRoot = (RelativeLayout) view.findViewById(R.id.mainrl);

and on Button click event put the following code:

 Snackbar.make(mRoot, "Had a snack at Snackbar", Snackbar.LENGTH_LONG).show();

Now main thing about this is:

just change current theme to Theme.AppCompat.Light.NoActionBar

It Done.!!!

SnackBar make method takes a view and from that view it trails up the heirarchy until it finds a suitable layout to show, if you had an exception this means that you didn't add CoordinatedLayout to your project

private static ViewGroup findSuitableParent(View view) {
        ViewGroup fallback = null;

        do {
            if(view instanceof CoordinatorLayout) {
                return (ViewGroup)view;
            }

            if(view instanceof FrameLayout) {
                // android.R.id.content
                if(view.getId() == 16908290) {
                    return (ViewGroup)view;
                }

                fallback = (ViewGroup)view;
            }

            if(view != null) {
                ViewParent parent = view.getParent();
                view = parent instanceof View?(View)parent:null;
            }
        } while(view != null);

        return fallback;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!