android 自定义Toast显示风格顶部弹出自定义时间

1.创建一个自己想要显示Toast风格的XML如下代码(toast_xml.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:orientation="horizontal"
    android:padding="10dp"
    android:background="#90000000"
    android:id="@+id/toast_layout_root">
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="8dp"
        android:id="@+id/iv"
        />
    <TextView android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>

 
2.封装一个Toast共同类,当然也可以直接在activity运用,那么我是用共通类,当然只是简单的封装:

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.zjtd.bzcommunity.R;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017/2/17.
 * Toast自定义工具类
 */
public class ToastCommom {
    private static TextView text;
    private static Toast toast;
    /**
     * 显示Toast
     * @param context
     * @param tvString
     * @param cntime
     */
    public static void ToastShow(Context context, String tvString, int cntime) {

        if (toast == null) {
            toast = new Toast(context);
            toast.setGravity(Gravity.TOP | Gravity.FILL_HORIZONTAL, 0, 0);
            toast.setDuration(Toast.LENGTH_LONG);
            View layout = LayoutInflater.from(context).inflate(R.layout.toast_xml, null);
//            ImageView mImageView = (ImageView) layout.findViewById(R.id.iv);
//            mImageView.setBackgroundResource(R.drawable.ic_launcher);
            text = (TextView) layout.findViewById(R.id.text);
            toast.setView(layout);
            showMyToast(toast, cntime);
        }
        text.setText(tvString);
        text.setTextColor(0xFFFFFFFF);
        text.setTextSize(16);
        if(toast!=null){
            toast.show();
        }

    }


    //自定义停留时间
    public static void showMyToast(final Toast toast, final int cnt) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }

        }, 0, 3000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }

        }, cnt);

    }

}


3:调用方法

 ToastCommom.ToastShow(this, "内容",3000);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值