情况:用户已登录,您显示了一个小吃店,上面写着成功登录,然后导航到另一个意图,但问题是当您导航时,小吃店被取消/销毁。我们如何使其跨活动持久化,就像Toast一样,无论导航到哪个活动,它都保持活动和健康,并遵循超时。
情况:用户已登录,您显示了一个小吃店,上面写着成功登录,然后导航到另一个意图,但问题是当您导航时,小吃店被取消/销毁。我们如何使其跨活动持久化,就像Toast一样,无论导航到哪个活动,它都保持活动和健康,并遵循超时。
<?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 thread that has not called Looper.prepare()错误
将showCustomToast函数中的代码放在这个run函数中
this.runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
实际上,SnackBar 不应该是持久的或者堆叠的,因为它们会覆盖屏幕上的其他元素。你可以在 Google Design 中看到这个规则。
但是你可以在这里使用第三方 Material Design 库:rey5137/material
你可以通过调用以下函数之一来显示它:
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();