Android 在活动中持久化 SnackBar [英] Android Persist A SnackBar Across Activities
问题描述
情况:用户已登录,您显示一个显示已成功登录的小吃店,然后导航到另一个意图,但问题是当您导航小吃店时,小吃店被取消/销毁.我们如何像 Toast 那样在活动中坚持它,无论您导航到什么活动..它保持活跃和健康并跟随它的超时.
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 .
推荐答案
您可以自定义类似于小吃店的吐司:
You can make a custom toast similar to the snack bar:
custom_toast.xml:
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>
并以这种方式显示:
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();
}
如果您收到 ERROR/AndroidRuntime(5176): Caused by: java.lang.RuntimeException: Can't create handler inside the thread that has not called Looper.prepare()
if you receive a ERROR/AndroidRuntime(5176): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
在此运行函数中将 showCustomToast 函数中的代码包裹起来,
wrap around the code inside showCustomToast function inside this run fuction,
this.runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
这篇关于Android 在活动中持久化 SnackBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!