您的位置:首页 > 其它

自定义Toast实现各种炫酷效果

2017-07-05 13:36 225 查看
在开发App的时候,提示信息必不可少。如何实现自定义的炫酷效果的Toast的呢。

下面是一个自定义的Toast效果,根据自己的需求实现各种炫酷效果。

下载地址:http://download.csdn.net/download/gl_mine_csdn/9889339 点击打开链接

public class MyToastUtils {
private static Toast mToast;
private static int mToastViewId = -1;//自定义提示的视图id
//开始显示toast
public static void show(Context context, String msg) {
if (TextUtils.isEmpty(msg)) return;
int duration;
if (msg.length() > 10) {
duration = Toast.LENGTH_LONG; //如果字符串比较长,那么显示的时间也长一些。
} else {
duration = Toast.LENGTH_SHORT;
}
if (mToast == null) {
mToast = Toast.makeText(context, msg, duration);
if (mToastViewId != -1) {
LayoutInflater inflate = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflate.inflate(mToastViewId, null);
TextView toast = (TextView) v.findViewById(R.id.toast);//r.id.toast 则为自己自定义的view布局的item
toast.setText(message);
mToast.setView(v);
}

} else
//r.id.toast 则为自己自定义的view布局的item
((TextView) mToast.getView().findViewById(R.id.toast)).setText(message);
mToast.setDuration(duration);
}
//居中显示
mToast.setGravity(Gravity.CENTER,0,0); mToast.show(); }

//自定义布局
public static void setmToastViewId(int mToastViewId) {
ToastUtils.mToastViewId = mToastViewId;
}
}

xml 文件  r.layout.toast
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:textSize="14sp"
android:textColor="#fff"
android:background="#000"/>

使用方式:
第一步 初始化  (设置了布局)
MyToastUtils.setmToastViewId(R.layout.toast);
第二步  使用方法
ToastUtils.show(context, "msg");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: