Toast在android中可谓是必备的交互形式,看厌倦了灰色的提示框和固定位置的显示,你有没有想过打造一个自己想要的显示效果呢?今天就来给大家介绍Toast自定义样式,自定义位置的使用,给我们的app添加一份专属的特效~~~~~~~~~~~
先来看下效果:
ok,先来看看传统的使用方式:Toast.makeText(context,text,time).show(),该方法中的3个参数分别为:上下文,需要显示的文字,显示的时间,其中显示时间有两种,一种是短的一种是长的,短的时间可以填0也可以填 Toast.LENGTH_SHORT,长的时间可以填1,也可以填Toast.LENGTH_LONG。下面接个性化的使用,首先是显示自定义的样式:
<?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:gravity="center"
android:orientation="vertical" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ccc"
android:src="@drawable/ic_launcher" />
</LinearLayout>
这个视图也可以通过自定义View的形式用代码得到,只要是一个View就可以了,MainActivity代码:
// 显示个性化的样式
public void showIndividuation(View view) {
// 先得到一个想要显示的View,可以通过XML文件定义,也可以自定义View
View tView = LayoutInflater.from(this).inflate(R.layout.custom_toast, null);
// 得到一个toast对象
Toast toast = new Toast(this);
// 设置显示的视图
toast.setView(tView);
// 设置显示时间
toast.setDuration(1);
// 设置显示的位置
toast.setGravity(Gravity.BOTTOM, 0, 20);
// 显示Toast
toast.show();
}
注意:使用自定义的View就不可以再调用Toast的MakeText方法,否者会报错。
扫描关注我的微信公众号:
自定义Toast的使用思路:new Toast--->setView()--->setDuration()--->setGravity()--->show();
其中setGravity方法有3个参数,第一个为显示的位置,后两个分别为x和y轴的偏移量。