我有一个ImageView的click事件调用openMenu()方法。我正在动画一个自定义视图,所以我在UI线程之外调用postInvalidateDelayed()方法,因为我的UI的其余部分在UI线程内部调用时稍微挂起。问题是在第一次单击ImageView时,Runnable线程实例被调用两次。第一次点击后,它只被调用一次,所以它完全正常,就像我想要的那样。
如何在第一次单击时阻止Runnable线程实例运行两次?
更新:由于一些奇怪的原因,它只在第一次安装应用程序时发生
public class MainMenu extends View {
private Bitmap bitmapMenu;
private DisplayMetrics displayMetrics;
int i;
int menuToggle=0,menuFlag=-1; //1 for open - 0 for close
float BitmapMaxTop;
boolean AnimationthreadFlag=true;
public MainMenu(Context context) {
super(context);
displayMetrics = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
i=displayMetrics.heightPixels;
bitmapMenu = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.main_menu),displayMetrics.widthPixels,(int) ((0.53f*displayMetrics.heightPixels)-MainActivity.actionbarHeight),false); //works on xperia API level 14
BitmapMaxTop=((0.53f*displayMetrics.heightPixels)-MainActivity.actionbarHeight);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(i>=BitmapMaxTop && menuFlag==1){
canvas.drawBitmap(bitmapMenu,0,i,null);
i-=10;
}
else if(menuFlag==-1){
canvas.drawBitmap(bitmapMenu,0,displayMetrics.heightPixels,null);
}
else{
canvas.drawBitmap(bitmapMenu,0,BitmapMaxTop,null);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return super.onTouchEvent(event);
}
void openMenu(){
menuFlag=1;
new Thread(new Runnable() {
int delay=1;
public void run() {
if(AnimationthreadFlag){ //true if animation thread is not running
AnimationthreadFlag=false;
for(int i=1;i<=2000;i++){
postInvalidateDelayed(delay);
delay+=1;
if(i==2000){
AnimationthreadFlag=true;
MainMenu.this.i=displayMetrics.heightPixels;
}
}
}
}
}).start();
}
}