项目中会经常用到Toast,为了满足项目的整体风格,往往会自定义Toast。今天就实现一个简单的自定义Toast
思路:1.继承Toast类,重写构造方法;
2.实现一个makeTest(Context context ,CharSequence text ,int duration)方法,返回Toast。具体实现:通过LayoutInflater将一个layout生成view对象
具体代码:
public class MyToast extends Toast{
private static Toast mToast;
public MyToast(Context context) {
super(context);
}
public static Toast makeText(Context context ,CharSequence text ,int duration){
if(mToast!=null){
mToast.cancel();
}
mToast=new Toast(context);
// 获取LayoutInflater
LayoutInflater inflater=LayoutInflater.from(context);
// 由layout创建一个view对象
View layout;
layout=inflater.inflate(R.layout.custom_my_toast,null);
TextView contentTextView= (TextView) layout.findViewById(R.id.tv_content);
contentTextView.setText(text);
mToast.setView(layout);
mToast.setDuration(duration);
return mToast;
}
}
背景的圆角是通过drawable配置文件实现
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ed6900"/>
<corners android:radius="6dip"/>
<padding android:bottom="0dip"
android:left="0dip"
android:right="0dip"
android:top="0dip"/>
</shape>
自定义toast对应的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_custom_toast">
<TextView
android:id="@+id/tv_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dip"
android:layout_marginBottom="4dip"
android:layout_marginRight="8dip"
android:layout_marginLeft="8dip"
android:textSize="18sp"
android:gravity="center"
android:textColor="#ffffff"/>
</LinearLayout>
使用非常简单,
MyToast.makeText(MainActivity.this ,"贱人薇薇" , Toast.LENGTH_SHORT).show();
有不清楚的地方欢迎留言!