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();  
    }  
}
posted @ 2016-02-29 16:43  VichanHo  阅读(432)  评论(0编辑  收藏  举报