Display Snackbar without CoordinatorLayout

前端 未结 4 1394
清歌不尽
清歌不尽 2021-02-06 00:20

I have Displayed Snackbar using CoordinatorLayout but in some layout i did\'t used CoordinatorLayout layout and i want to display snackbar but faced problem with it.

I h

相关标签:
4条回答
  • 2021-02-06 00:39

    As others suggest best solution to do this is via method mentioned before. I would add and option to show SnackBar with button to dismiss SnackBar. This comes useful when you'd like to give user time to read your message and then acknowledge your application that your user read your message.

       public void setSnackBar(View root, String textToDisplay) {
        Snackbar snackbar = Snackbar.make(root, textToDisplay, Snackbar.LENGTH_INDEFINITE);
        snackbar.setAction("OK", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                snackbar.dismiss();
                //your other action after user hit the "OK" button
            }
        });
        snackbar.show();
    
    0 讨论(0)
  • 2021-02-06 00:40
    public static void setSnackBar(View root, String snackTitle) {
      Snackbar snackbar = Snackbar.make(root, snackTitle, Snackbar.LENGTH_SHORT);
      snackbar.show();
      View view = snackbar.getView();
      TextView txtv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
      txtv.setGravity(Gravity.CENTER_HORIZONTAL);
    }
    

    Just call the above method and pass any parent layout such as LinearLayout, RelativeLayout or ScrollView, for example:

    setSnackBar(layout,"This is your SnackBar");  //here "layout" is your parentView in a layout
    

    Do not forget to find your view using findViewById().

    0 讨论(0)
  • 2021-02-06 00:56

    use this view instance of CoordinatorLayout:

    View view = findViewById(android.R.id.content);
    Snackbar snackbar = Snackbar.make(view, "your text", Snackbar.LENGTH_SHORT);
    snackbar.show();
    
    0 讨论(0)
  • 2021-02-06 00:57

    Try this easy piece of code.. a dummy view from the android framework itself is used

    Snackbar.make(findViewById(android.R.id.content),"Your Text Here",Snackbar.LENGTH_SHORT).show();

    0 讨论(0)
提交回复
热议问题