Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Snack bar not displayed

I'm inheriting from BaseActivity for all the other activities.

public class BaseActivity extends AppCompatActivity {

    public static CoordinatorLayout coordinatorLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        coordinatorLayout = (CoordinatorLayout) findViewById(R.id
                .coordinatorLayout1);
    }
}

activity_base.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/coordinatorLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.Activity.BaseActivity"> 
</android.support.design.widget.CoordinatorLayout>

Snackbar is not displayed when tried to access from a non-activity class.

Snackbar snackbar = Snackbar.make(
        BaseActivity.coordinatorLayout,
        "Helooo....",
        Snackbar.LENGTH_LONG
);
like image 906
user1382802 Avatar asked Dec 27 '15 05:12

user1382802


People also ask

What is Snack bar android?

Snackbar in android is a new widget introduced with the Material Design library as a replacement of a Toast. Android Snackbar is light-weight widget and they are used to show messages in the bottom of the application with swiping enabled. Snackbar android widget may contain an optional action button.

How to display a message in android?

Display a message There are two steps to displaying a message. First, you create a Snackbar object with the message text. Then, you call that object's show() method to display the message to the user.


2 Answers

private static final String message = "No Internet Connection";

public  static void message(Activity activity) {
    View rootView = activity.getWindow().getDecorView().findViewById(android.R.id.content);
    Snackbar.make(rootView, message, Snackbar.LENGTH_LONG).show();
}
like image 74
chintan Avatar answered Oct 31 '22 22:10

chintan


Make a public method in a Util class and dont make the cordinatorLayout as public static. Keep the weakReference of your Activity's instance and through that you can show the SnackBar. Method given below.

public void showSnackBar(Activity activity, String message){
    View rootView = activity.getWindow().getDecorView().findViewById(android.R.id.content);
    Snackbar.make(rootView, message, duration).show();
}
like image 22
Mohammed Rampurawala Avatar answered Oct 31 '22 22:10

Mohammed Rampurawala