Reputation: 604
Situation : User has logged in , you show a snack bar which says successfully logged in and then navigate to another intent but the problem is that when you navigate the snackbar is cancelled / destroyed . how do we persist it across activities like the way a Toast does , no matter what activity you navigate to .. it stays alive and healthy and follows it's timeout .
Upvotes: 6
Views: 6083
Reputation: 180
You can make a custom toast similar to the snack bar:
custom_toast.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toast_layout"
android:layout_gravity="bottom|center_horizontal"
android:background="#545454"
android:gravity="left|fill_vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="@+id/toast_text"
android:layout_gravity="bottom"
android:textColor="#ffffff"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="8dp" />
</LinearLayout>
and show it this way:
public void showCustomToast(String msg)
{
//inflate the custom toast
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.custom_toast,(ViewGroup) findViewById(R.id.toast_layout));
TextView text = (TextView) layout.findViewById(R.id.toast_text);
// Set the Text to show in TextView
text.setText(msg);
Toast toast = new Toast(getApplicationContext());
//Setting up toast position, similar to Snackbar
toast.setGravity(Gravity.BOTTOM | Gravity.LEFT | Gravity.FILL_HORIZONTAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
if you receive a ERROR/AndroidRuntime(5176): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
wrap around the code inside showCustomToast function inside this run fuction,
this.runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
Upvotes: 4
Reputation: 9142
In fact, SnackBar should not be persistent or be stacked, as they are above other elements on screen. You can see this rule in Google Design
But you can use a third party Material Design library here: rey5137/material
You can show it by call one of following functions:
public void show(Activity activity);
//parent should be FrameLayout or RelativeLayout so SnackBar can algin bottom.
public void show(ViewGroup parent);
// It only work if SnackBar is already attached to a parent view.
public void show();
Upvotes: 0
Reputation: 15668
Make a wrapper around your view group and add it in each of your layouts. You can also use a window overlay. See here
Upvotes: 0