简单自定义Toast,实现好看的消息提示框
一般系统给我们的Toast都是黑色的 比较不美观,所以作为一名新晋的博主,就和大家一起分享分享我的开发小经验,当然各位老鸟如果有更好的方法,欢迎在下方评论。
自定义Toast还是比较容易的
步骤1、写一个需要显示的布局xml
步骤2、使用LayoutInflater得到xml布局转化为View
步骤3、实例一个Toast,使用setView()方法设置需要显示的View
*************************先来展示一下效果图******************************
是不是比系统的Toast好看多啦 ,其实实现起来特别简单的
爆代码啦!!!!!!!!!!!!
1、布局文件 login_message.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/login_message" > <TextView android:id="@+id/error" android:layout_width="match_parent" android:layout_height="wrap_content" android:drawableLeft="@drawable/hbl" android:layout_marginLeft="10dp" android:paddingTop="10dp" android:layout_marginRight="10dp" android:paddingBottom="10dp" android:textColor="#fff" android:text=" 显示信息" android:gravity="center_vertical" /> </LinearLayout>
2、资源文件
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape> <corners android:radius="10dp"/> <solid android:color="#b94bb4dd"/> </shape> </item> </selector>
3、java代码
//获取布局xml View tempView=LayoutInflater.from(login_activity.this).inflate(R.layout.login_message,null); TextView textView=(TextView) tempView.findViewById(R.id.error); //添加需要显示的信息 textView.setText(" 请使用正确的姿势登录QQ!"); Toast toast = new Toast(login_activity.this); //显示在屏幕的中间 toast.setGravity(Gravity.CENTER, 0, 0); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(tempView); toast.show();
好啦 就是这么简单 对你有帮助的话就顶一下哦