最简单的安卓开发自定义Toast显示时间(使用Java定时器实现)
1.新建类继承TimerTask
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class toastTask extends TimerTask {
Toast toast;
Timer timer;
@Override
public void run() {
toast.cancel();
timer.cancel();
timer.purge();
}
public toastTask(Toast toast) {
this.toast = toast;
}
public void setTimer(Timer timer) {
this.timer = timer;
}
}
2.再新建一个控制Toast显示的类
import android.content.Context;
import android.widget.Toast;
import java.util.Timer;
public class new_Toast {
private String str;
private long time = 800;
private Context context;
public new_Toast(String str, long time, Context context) {
this.str = str;
this.time = time;
this.context = context;
}
public new_Toast setStr(String str) {
this.str = str;
return this;
}
public new_Toast setTime(long time) {
this.time = time;
return this;
}
public new_Toast setContext(Context context) {
this.context = context;
return this;
}
public new_Toast(Context context) {
this.context = context;
}
public void start() {
Timer timer = new Timer();
Toast toast = Toast.makeText(context, str, Toast.LENGTH_SHORT);
toast.show();
toastTask toastTask = new toastTask(toast);
toastTask.setTimer(timer);
timer.schedule(toastTask,time);
}
}
3.在方法里实例化类然后调用
调用的时候可以设置内容和时间,但是设置时间不要超过2s,如果需要长时间的话可以在timer里面传入循环调用的时间(我也没试过)。
这样虽然可以实现但是不知道有什么别的问题,凑合能用就行了。