我正在尝试管理一个可与许多按钮一起使用的多任务应用程序。
为此,我做了这个功能:
public boolean isTouched(View view, MotionEvent event) {
boolean touched = false;
int count = event.getPointerCount();
int[] location = { 0, 0 };
view.getLocationOnScreen(location);
Point min = new Point(location[0], location[1]);
Point max = new Point(min.x + view.getWidth(), min.y + view.getHeight());
for (int i = 0; i < count; i++) {
int rawX = (int) event.getX(i);
int rawY = (int) event.getY(i);
if(rawX>=min.x && rawX<=max.x && rawY>=min.y && rawY<=max.y){
//Log.d("mylog", "***Found a view: " + v.getId());
touched = true;
if (event.getAction() == MotionEvent.ACTION_UP) touched = false;
}
}
return touched;
}
以及拦截onTouchEvent和管理两个ImageView的activity的函数override
@Override
public boolean onTouchEvent (MotionEvent event) {
if (isTouched(button1,event)) {
// it is pressed
if ((Integer)button1.getTag() == 0) { // but before wasn't pressed
mp1.start();
button1.setBackgroundResource(R.drawable.happy_on);
button1.setTag(1);
// start music 1
}
} else {
// it isn't pressed
if ((Integer)button1.getTag() == 1) { // and before it was pressed
mp1.stop();
try {
mp1.prepare();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
Log.e("hb","illegal state exception mp2") ;
mp1= MediaPlayer.create(getBaseContext(), R.raw.female01) ;
}
button1.setBackgroundResource(R.drawable.happy_off);
button1.setTag(0);
// stop music 1
}
}
if (isTouched(button2,event)) {
// it is pressed
if ((Integer)button2.getTag() == 0) { // but before wasn't pressed
mp2.start();
button2.setBackgroundResource(R.drawable.to_on);
button2.setTag(1);
// start music 2
}
} else {
// it isn't pressed
if ((Integer)button2.getTag() == 1) { // and before it was pressed
mp2.stop();
try {
mp2.prepare();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
Log.e("hb","illegal state exception mp2") ;
mp2= MediaPlayer.create(getBaseContext(), R.raw.female02) ; }
button2.setBackgroundResource(R.drawable.to_off);
button2.setTag(0);
// stop music 1
}
}
return false;
}
按钮(我使用 imageview)像钢琴键盘一样被按下:你可以用一根、两根手指将它传递过来,当指针进入视图时,异步操作就会开始。在 event_up 或指针离开按钮时,动作停止。
它有效,但它是一种非常缓慢的方法:它被许多 action_move 事件淹没。
任何人都可以知道一种优化这种多点触控管理方式的方法吗?
编辑:mp1 和 mp2 是 mp3 媒体播放器对象。当我在不释放指针的情况下从一个按钮传递到另一个按钮时,它可以工作,但是会有几毫秒的间隙使旋律跳跃。我要做的效果就像钢琴的键盘,没有间隙。
我认为差距是为函数isTouched的权重产生的。我怎样才能减少这个重量?
谢谢