怎么改变Android默认Toast的颜色和大小,自定义我们自己需要的效果
思路:我在这里封装了一个Toast工具类,这样在想用时,直接调用里面的方法就ok了!
有两个方法:第一个是文本加图片显示的,第二个是纯文本显示的。
上代码。。。
public class ToastUtil {
//显示文本+图片的Toast
public static void showImageToas(Context context,String message){
View toastview= LayoutInflater.from(context).inflate(R.layout.toast_image_layout,null);
TextView text = (TextView) toastview.findViewById(R.id.tv_message);
text.setText(message); //要提示的文本
Toast toast=new Toast(context); //上下文
toast.setGravity(Gravity.CENTER,0,0); //位置居中
toast.setDuration(Toast.LENGTH_SHORT); //设置短暂提示
toast.setView(toastview); //把定义好的View布局设置到Toast里面
toast.show();
}
//显示文本的Toast
public static void showTextToas(Context context,String message){
View toastview= LayoutInflater.from(context).inflate(R.layout.toast_text_layout,null);
TextView text = (TextView) toastview.findViewById(R.id.tv_message);
text.setText(message);
Toast toast=new Toast(context);
toast.setGravity(Gravity.CENTER,0,0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(toastview);
toast.show();
}
}
图片+文本的布局代码 toast_image_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/bg_toast"
android:gravity="center">
<ImageView
android:layout_width="match_parent"
android:layout_height="35dp"
android:padding="5dp"
android:layout_gravity="center"
android:src="@drawable/icon_ok"/>
<TextView
android:id="@+id/tv_message"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:text="Toast"
android:padding="5dp"
android:textSize="16sp"
/>
</LinearLayout>
纯文本的布局代码 toast_text_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@drawable/bg_toast"
android:gravity="center">
<TextView
android:id="@+id/tv_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/white"
android:text="Toast"
android:paddingTop="10dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:paddingBottom="15dp"
android:textSize="16sp"
/>
</LinearLayout>
布局用到的背景需要自定义形状shape,在res文件下的drawable中new一个Drawable resource file,名称为bg_toast,贴上代码
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="@color/orange"/>
<corners android:bottomLeftRadius="20dp"
android:bottomRightRadius="20dp"
android:topLeftRadius="20dp"
android:topRightRadius="20dp"/>
</shape>
走到这里就是万事具备,直接调用相应的方法就可以了!