gpt4 book ai didi

Android 在 Activity 中持久化一个 SnackBar

转载 作者:太空宇宙 更新时间:2023-11-03 10:18:40 25 4
gpt4 key购买 nike

情况:用户已登录,您显示一个提示已成功登录的 snackbar ,然后导航到另一个 Intent ,但问题是当您导航时, snackbar 被取消/销毁。我们如何像 Toast 那样在 Activity 中持久保存它,无论您导航到什么 Activity ..它都保持活跃和健康并遵循它的超时。

最佳答案

可以做一个类似于 snackbar 的自定义 toast :

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 thread that has not called Looper.prepare()

在此运行函数中将 showCustomToast 函数中的代码包裹起来,

this.runOnUiThread(new Runnable() {
@Override
public void run() {

}

});

关于Android 在 Activity 中持久化一个 SnackBar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29989631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com