日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

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

编程问答

android中对Toast的简单封装

發布時間:2025/7/14 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的简单封装的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。