android自定义自定义Toast设定显示时间设定显示时间
主要为大家详细介绍了android自定义Toast设定显示时间,具有一定的参考价值,感兴趣的小伙伴们可以参考一
下
开发android的同学可能会抱怨Toast设定显示的时长无效,只能是Toast.LENGTH_LONG 或者Toast.LENGTH_SHORT 之
一,为了解决这些办法,有多种实现方式:
1.使用定时器,定时调用show()方法.
2.使用CountDownTimer类,也是调用show()方法.
3.使用WindownManager类实现.
本文使用方法三进行实现,难度不大,直接看代码吧.
package com.open.toast;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* 自定义时长的Toast
* @author DexYang
*
*/
public class CToast {
public static CToast makeText(Context context, CharSequence text, int duration)
{
CToast result = new CToast(context);
LinearLayout mLayout=new LinearLayout(context);
TextView tv = new TextView(context);
tv.setText(text);
tv.setTextColor(Color.WHITE);
tv.setGravity(Gravity.CENTER);
mLayout.setBackgroundResource(R.drawable.widget_toast_bg);
int w=context.getResources().getDisplayMetrics().widthPixels / 2;
int h=context.getResources().getDisplayMetrics().widthPixels / 10;
mLayout.addView(tv, w, h);
result.mNextView = mLayout;
result.mDuration = duration;
return result;
}
public static final int LENGTH_SHORT = 2000;
public static final int LENGTH_LONG = 3500;
private final Handler mHandler = new Handler();
private int mDuration=LENGTH_SHORT;
private int mGravity = Gravity.CENTER;
private int mX, mY;
private float mHorizontalMargin;
private float mVerticalMargin;
private View mView;
private View mNextView;
private WindowManager mWM;
private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
public CToast(Context context) {
init(context);
}
/**
* Set the view to show.
* @see #getView
评论0