【问题标题】:Android - Custom Toast touch outside eventAndroid - 自定义 Toast 触摸外部事件
【发布时间】:2015-05-11 07:54:31
【问题描述】:

我正在尝试使用带有ImageViewTextView自定义吐司。 我希望我的 Toast 在我触摸任何地方(单击按钮、触摸布局...)时消失,但它不会。

在调用新的 Toast 之前,我阅读了 Toast.class 文件并尝试使用 cancel() 方法,但这并没有解决任何问题。谁能给我一个解决方案?

我的CustomToast.java

LayoutInflater inflater = (LayoutInflater) context.getSystemService(
        Context.LAYOUT_INFLATER_SERVICE);
View v = new View(context);
v = inflater.inflate(R.layout.custom_toast, (ViewGroup) v.findViewById(
        R.id.layout_custom_toast));

layout = (RelativeLayout) v.findViewById(R.id.layout_custom_toast);
tvToast = (TextView) v.findViewById(R.id.tv_custom_toast);
tvToast.setText(text);

ivToast = (ImageView) v.findViewById(R.id.iv_custom_toast);
layout.setBackgroundResource(R.drawable.border_style_red);
ivToast.setBackgroundResource(R.drawable.warning);

Toast toast = new Toast(context);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(v);
toast.show();

【问题讨论】:

  • 你见过这个问题吗? stackoverflow.com/q/10070108/1979347
  • 解决方案是基于(可解雇的)AlertDialog 构建一个Toast。很多关于它的教程和问题。
  • 感谢您的回复。 @shkschneider - 我通过使用 Toast.makeText(...) 初始化 toast 对象、删除所有视图并添加 ImageView 和 TextView 解决了这个问题。
  • 很高兴你解决了它。将您的解决方案发布为答案,然后自己接受以关闭此问题。

标签: android toast android-toast


【解决方案1】:

解决方案:我使用Toast.makeText(...) 而不是new Toast(..),因为它会膨胀隐藏 api(com.android.internal.R) 中的资源并且您无法访问它。使用Toast.makeText(...) 初始化 toast 对象可以让您轻松访问隐藏的 api。

Toast toast = Toast.makeText(context, text, duration);

layout = (LinearLayout) toast.getView();
layout.removeAllViews();
layout.setOrientation(LinearLayout.HORIZONTAL);

int dftPadding = (int) StaticValues.dpToPixel(context, 10);
layout.setPadding(dftPadding, dftPadding, dftPadding, dftPadding);
ivToast = new ImageView(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, (int) StaticValues.dpToPixel(context, 5), 0);
ivToast.setLayoutParams(params);
layout.setBackgroundResource(R.drawable.border_style_red);
ivToast.setBackgroundResource(R.drawable.warning);
layout.addView(ivToast);
tvToast = new TextView(context);
tvToast.setTextColor(Color.BLACK);
tvToast.setTypeface(null, Typeface.BOLD);
tvToast.setText(text);
layout.addView(tvToast);
toast.show();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多