自定义Toast

默认的Toast不能满足所有开发使用,所以抛出一个可以自定义布局与位置的Toast
首先Toast的画出布局toast.xml:




    


在drawable文件夹下指定布局背景样式(也可以不指定)toaststyle.xml



    
    
    
    


布局和样式都是可以自己定义的
然后就是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:[email protected]
 */
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就完成了

你可能感兴趣的:(自定义Toast)