android中对Toast的简单封装
生活随笔
收集整理的這篇文章主要介紹了
android中对Toast的简单封装
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
// 一般做法
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" > //可以根據(jù)實(shí)際情況來(lái)自定義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(); } }轉(zhuǎn)載于:https://www.cnblogs.com/VichanHo/p/5227970.html
總結(jié)
以上是生活随笔為你收集整理的android中对Toast的简单封装的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据库的优化tips
- 下一篇: Elasticlunr.js 简单介绍