Android 在 Activity 中持久化一个 SnackBar

标签 android user-interface

情况:用户已登录,您显示一个提示已成功登录的 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/

相关文章:

java - 如何验证来自 SWT 文本小部件的输入并分配给变量?

c# - Unity - 检查鼠标点击是否在矩形变换内

android Wifilock-移动数据访问锁怎么样?

java - 为什么每次执行 ActionListener 时我的 GUI 窗口都会卡住?

java - 我创建了一个类来显示对话框并调用 Activity main 中的函数,但它不起作用

android - 通过单击/触摸外部 : 删除 fragment

python - 我如何在pyqt中集成一个定时循环

java - 如何将来自不同 Jframe 的所有数据保存在 java GUI 中的一个对象中

android - Lucky Patcher 会放弃它修补的应用程序并且 Google API 会验证 SHA1 吗?

android - 在 Android Studio 版本 3.2 和 Gradle 版本 4.6 中启用缩小时,Gradle 构建因 fabric crashlytics 而失败