欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

android中对Toast的简单封装

发布时间:2025/7/14 编程问答 49 豆豆
生活随笔 收集整理的这篇文章主要介绍了 android中对Toast的简单封装 小编觉得挺不错的,现在分享给大家,帮大家做个参考.
// 一般做法 public void showToast(Context context, String msg) { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); }

===============华丽的分割线===============

// 如果Activity或Fragment有继承基类,则在基类中变成 public void showToast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } 或 public void showToast(String msg) { Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show(); }

===============华丽的分割线===============

// 如果有自定Application的话,譬如: public class MyApplication extends Application { private static Context mContext; @Override public void onCreate() { super.onCreate(); mContext = getApplicationContext(); } public static Context getContext() { return mContext; } } // 则可以自定义ToastUtil类 class ToastUtil{public static void show(String msg) { Toast.makeText(MyApplication.getContext(), msg, Toast.LENGTH_SHORT).show(); } }

===============华丽的分割线===============

res/drawable/toast_custom_bg.xml

<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > //可以根据实际情况来自定义Toast的显示样式 <solid android:color="#ff5252" /> <corners android:radius="5dp" /> <padding android:bottom="10dp" android:left="15dp" android:right="15dp" android:top="10dp" /> </shape>

res/layout/toast_custom.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/toast_custom_bg" android:orientation="vertical" > <TextView android:id="@+id/tv_toast" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/white" android:textSize="16sp" /> </LinearLayout>

最后就可以自定义Toast的显示样式了:

class ToastUtil{public static void show(String msg) { LinearLayout v = (LinearLayout) LinearLayout.inflate(MyApplication.getContext(), R.layout.toast_custom, null); TextView tv_toast = (TextView) v.findViewById(R.id.tv_toast); tv_toast.setText(msg); Toast toast = new Toast(MyApplication.getContext()); toast.setGravity(Gravity.CENTER, 0, 0);//可以自定义Toast显示在屏幕上的位置 toast.setDuration(Toast.LENGTH_SHORT); toast.setView(v); toast.show(); } }

转载于:https://www.cnblogs.com/VichanHo/p/5227970.html

总结

以上是生活随笔为你收集整理的android中对Toast的简单封装的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。