以前就看着google提供的原生Toast太丑了,就一个黑框;所以我灵机一动看了Toast的源码,看到了两个方法:
//这个方法可以用来设置自定义的布局,然后用布局加载器获取一个View对象
public void setView(View view) {
throw new RuntimeException("Stub!");
}
//这个就是用来设置Toast弹出的位置
public void setGravity(int gravity, int xOffset, int yOffset) {
throw new RuntimeException("Stub!");
}
有了上面的两个方法我们就可以开工了,下面这个类其实就是一个简单的辅助类,你可以根据自己的需求进行扩展,具体实现如下:
/**
*@author jiangrongtao
*
*csdn:http://blog.csdn.net/jiang_rong_tao
*
*github:https://github.com/jiangrongtao/jiangrongtao.github.io
*
* created at 2016/6/28 17:20
*/
public class SmartToast {
private static SmartToast mSmartToast=new SmartToast();
private ISmartToast mISmartToast;
private SmartToast(){}
public static SmartToast getInstance(){
return mSmartToast;
}
/**
* 显示自定义样式的Toast,如果
* @param context
* @param deftext 默认要显示的文字
*/
public void showToast(Context context,CharSequence deftext){
Toast t = Toast.makeText(context, deftext, Toast.LENGTH_SHORT);
if (mISmartToast!= null) {
//在回调接口中做View的显示的具体操作
View inflate=mISmartToast.showSuccessView();
if (inflate!=null) {
t.setGravity(Gravity.CENTER, 0, 0);
t.setView(inflate);
}
}
t.show();
}
public void setISmartToast(ISmartToast iSmartToast){
this.mISmartToast=iSmartToast;
}
}
听取了朋友的建议,我给多加了一个接口回调的方法用来自定义布局;
/**
* Created by rongtao on 2016/6/30.
*/
public interface ISmartToast {
View showSuccessView();
}
布局文件toast_layout.xml如下
<?xml version="1.0" encoding="utf-8"?>
<com.rongtao.vectortest.CardVoucherView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#44ff33cf"
android:padding="20dp"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/a_bg"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold|italic"
android:text="toast对话框"
android:layout_marginLeft="8dp"
/>
</com.rongtao.vectortest.CardVoucherView>
其中上面用到的CardVoucherView是在我以前的blog:
http://blog.csdn.net/jiang_rong_tao/article/details/51489862
中的自定义view,为了效果风骚一点,所以我选择了用它,也是对以前知识的回顾。
在Button的点击事件中弹出Toast:
//修改后的使用方法
SmartToast instance = SmartToast.getInstance();
instance.setISmartToast(new ISmartToast() {
@Override
public View showSuccessView() {
View inflate = View.inflate(MainActivity.this, R.layout.toast_layout, null);
return inflate;
}
});
instance.showToast(this,"俺是默认的文本");
很期待效果吧。。。下面就是
如果加载自定义布局失败的时候显示默认的黑框效果。
其实并不风骚,就是一种灵感而已。
总结:
- 要实现不同的样式,自己修改toast_layout.xml文件,然后调用setView()方法即可;
- 要控制Toast弹出的位置,setGravity()即可。