三、自定义Toast (可以播放音乐)
/** * 新数据Toast提示控件(带音乐播放) * @author liux (http://my.oschina.net/liux) * @version 1.0 * @created 2012-8-30 */ public class NewDataToast extends Toast{ private MediaPlayer mPlayer; private boolean isSound; public NewDataToast(Context context) { this(context, false); } public NewDataToast(Context context, boolean isSound) { super(context); this.isSound = isSound; mPlayer = MediaPlayer.create(context, R.raw.newdatatoast);
//播放结束后立即释放播放器资源 mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){ @Override public void onCompletion(MediaPlayer mp) { mp.release(); } }); } @Override public void show() { super.show(); if(isSound){ mPlayer.start(); } } /** * 设置是否播放声音 */ public void setIsSound(boolean isSound) { this.isSound = isSound; } /** * 获取控件实例 * @param context * @param text 提示消息 * @param isSound 是否播放声音 * @return */ public static NewDataToast makeText(Context context, CharSequence text, boolean isSound) { NewDataToast result = new NewDataToast(context, isSound); LayoutInflater inflate = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); DisplayMetrics dm = context.getResources().getDisplayMetrics(); //自定义toast布局 View v = inflate.inflate(R.layout.new_data_toast, null); v.setMinimumWidth(dm.widthPixels);//设置控件最小宽度为手机屏幕宽度 TextView tv = (TextView)v.findViewById(R.id.new_data_toast_message); tv.setText(text); result.setView(v);
result.setDuration(600);//设置显示时间 result.setGravity(Gravity.TOP, 0, (int)(dm.density*75));//设置toast显示位置 return result; } }