自定义控件:Toast

来源:互联网 发布:大学生网络党校考试 编辑:程序博客网 时间:2024/06/07 00:44

比较简单,直接贴代码

效果图

这里写图片描述

toast的布局:custom_toast.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:gravity="center"    android:background="@drawable/custom_toast"    android:orientation="horizontal">    <ImageView        android:id="@+id/iv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:background="@mipmap/ic_launcher"/>    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:textColor="@android:color/white"        android:textSize="20sp"        android:layout_height="wrap_content"        android:text=""/></LinearLayout>

custom_toast.xml

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android">    <corners android:radius="10dp"/>    <solid android:color="#21211d"/></shape>

CustomToast

public class CustomToast {    private static Toast toast;    public static void showToast(Context context, String content) {        if (toast == null) {            View toastView = LayoutInflater.from(context).inflate(R.layout.custom_toast, null);//          ImageView iv = (ImageView) toastView.findViewById(R.id.iv);            TextView tv = (TextView) toastView.findViewById(R.id.tv);            tv.setText(content);            toast = new Toast(context);            toast.setDuration(Toast.LENGTH_SHORT);            toast.setView(toastView);            toast.setGravity(Gravity.CENTER, 0, 0);        }        toast.show();    }}

Toast居中

Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);toast.setGravity(Gravity.CENTER,0,0);

使用

CustomToast.showToast(MainActivity.this,"已达到北京");

其它

Demo:http://git.oschina.net/customView/customtoast01
参考:自定义Toast样式

原创粉丝点击