自定义Toast
2017-06-05 本文已影响0人
5e1b18effb55
默认的Toast不能满足所有开发使用,所以抛出一个可以自定义布局与位置的Toast
首先Toast的画出布局toast.xml:
<?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:background="@drawable/toaststyle"
android:orientation="vertical">
<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
android:shadowColor="#BB000000"
android:shadowRadius="2.75"
android:textColor="@android:color/white" />
</LinearLayout>
在drawable文件夹下指定布局背景样式(也可以不指定)toaststyle.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#666" />
<!-- 描边 -->
<stroke
android:width="0.33dp"
android:color="#dedede" />
<corners
android:bottomLeftRadius="5dp"
android:bottomRightRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp" />
</shape>
布局和样式都是可以自己定义的
然后就是Java代码了(CustomToast.java)
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by jiangtao on 2017/6/5 14:35
* E-mail:3305727299@qq.com
*/
public class CustomToast {
public static void makeText(Context context, String message) {
View view = LayoutInflater.from(context).inflate(R.layout.toast, null);
((TextView) view.findViewById(R.id.message)).setText(message);
Toast toastStart = new Toast(context);
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
int height = wm.getDefaultDisplay().getHeight();
toastStart.setGravity(Gravity.TOP, 0, height / 3);
toastStart.setDuration(Toast.LENGTH_LONG);
toastStart.setView(view);
toastStart.show();
}
}
OK,一个自定义布局样式的Toast就完成了