Toast:前后台弹出Toast不一致?

QuibblerQuibbler 2020-04-12 约 6 分钟 2060 次阅读

Toast:前后台弹出Toast不一致?

Toast不用再多说了,Android中非常常见的轻量级提醒。用法很简单,但是周末无意中发现一个Toast提示信息和实际代码中的不一样。难道自己又遇到“玄学”问题了?

1、Toast源码

正常弹出Toast很简单,一行代码的事情。源码如下,第二个参数CharSequence text就是设置Toast显示的文字信息。

public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
        return makeText(context, null, text, duration);
    }
    
    public static Toast makeText(@NonNull Context context, @Nullable Looper looper,
            @NonNull CharSequence text, @Duration int duration) {
        Toast result = new Toast(context, looper);
        LayoutInflater inflate = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
        TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
        tv.setText(text);
        result.mNextView = v;
        result.mDuration = duration;
        return result;
    }

2、实际Toast

Toast.makeText(context, "后台弹出Toast", Toast.LENGTH_SHORT).show();

但是发现弹出的和显示的不一样,前面多了应用名:


当应用在前台能看见的时候弹出的Toast信息就是传入的text内容。

猜测:各个手机厂商在二次开发Android ROM框架的时候加上了一些判断,当Toast是由在后台的APP弹出时加上应用名,方便用户知道到底是谁在提示。而应用在前台的时候就没这个必要了。

3、处理方法

也不是没有办法,从Toast的源码可以看到内部是对一个TextView设置text。而刚好Toast也提供了一个setText()方法,内部也是获得这个TextView com.android.internal.R.id.message对其设置CharSequence text。

public void setText(CharSequence s) {
        if (mNextView == null) {
            throw new RuntimeException("This Toast was not created with Toast.makeText()");
        }
        TextView tv = mNextView.findViewById(com.android.internal.R.id.message);
        if (tv == null) {
            throw new RuntimeException("This Toast was not created with Toast.makeText()");
        }
        tv.setText(s);
    }

改进的Toast方法:

Toast toast = Toast.makeText(context, null, Toast.LENGTH_SHORT);
    toast.setText("后台Toast");
    toast.show();

相关文章:

        Toast Notifications 

         Docs > Reference > Toast">Android Developers > Docs > Reference > Toast

        Toast默认加了App名字怎么搞

        Android Toast显示应用名(小米手机)

相关推荐

WilliamChart:轻量美观的 Android 图表库实战
精选开源

WilliamChart:轻量美观的 Android 图表库实战

WilliamChart:轻量美观的 Android 图表库实战数据可视化是运动、健康、金融、统计类 App 的刚需。MPAndroidChart 功能最全但偏重复杂,WilliamChart 走的则是"轻量 + 美观 + Kotlin 原生"路线——v3 用 Kotlin 完全重写,API 极简,一行 chart.animate(dataSet) 就能把数据画成带动画的折线/柱状/环形图,开箱即

175