Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Persist A SnackBar Across Activities

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 .

like image 429
TheAnimatrix Avatar asked Sep 28 '22 02:09

TheAnimatrix


1 Answers

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() {

    }

});
like image 174
Myke Dev Avatar answered Oct 06 '22 18:10

Myke Dev