自定义控件:Toast

xiaoxiao2021-02-27  139

比较简单,直接贴代码

效果图

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样式

转载请注明原文地址: https://www.6miu.com/read-15684.html

最新回复(0)