我将从BaseActivity继承所有其他活动.
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.
Snackbar snackbar = Snackbar.make( BaseActivity.coordinatorLayout,"Helooo....",Snackbar.LENGTH_LONG );
解决方法
在Util类中创建一个公共方法,不要将cordinatorLayout设为public static.保留Activity的实例的weakReference,然后通过它可以显示SnackBar.
方法如下.
方法如下.
public void showSnackBar(Activity activity,String message){ View rootView = activity.getWindow().getDecorView().findViewById(android.R.id.content); Snackbar.make(rootView,message,duration).show(); }