user1382802 user1382802 - 3 months ago 12
Android Question

Snack bar not displayed

I'm using a base activity for all the other activity.

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



<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);
snackbar.show();

Answer

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();
}
Comments