以下是代码:
public class MainActivity extends Activity implements OnTouchListener {
RelativeLayout rl;
int i, j = 0;
final int imageArray[] = { R.drawable.w1, R.drawable.w2, R.drawable.w3 };
int image;
final int imageCount = 3;
ImageView back, save, next;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
final int imageArray[] = { R.drawable.w1, R.drawable.w2, R.drawable.w3 };
image = imageArray[0];
rl = (RelativeLayout) findViewById(R.id.rlBackground);
back = (ImageView) findViewById(R.id.bBack);
save = (ImageView) findViewById(R.id.bSave);
next = (ImageView) findViewById(R.id.bNext);
back.setOnTouchListener(this);
save.setOnTouchListener(this);
next.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bBack:
if (j == 0) {
j = imageCount;
}
image = imageArray[j - 1];
rl.setBackgroundResource(image);
j = j - 1;
break;
case R.id.bSave:
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 2;
Bitmap bm = BitmapFactory.decodeResource(getResources(), image,
opts);
// savePicture(bm, "image_name.jpg");
SaveImage savefile = new SaveImage();
savefile.SaveImagee(this, bm);
Toast.makeText(getApplicationContext(),
"Image saved on your gallery!", Toast.LENGTH_LONG).show();
break;
case R.id.bNext:
if (j != imageCount) {
rl.setBackgroundResource(imageArray[j]);
image = imageArray[j];
j = j + 1;
} else {
j = 0;
rl.setBackgroundResource(imageArray[j]);
image = imageArray[j];
j = j + 1;
}
break;
}
return false;
}
}
问题:如果我点击“保存”按钮,它会在第一次点击时起作用。如果我单击下一个按钮,我需要单击它两次以触发该功能,但在此之后,如果我继续单击下一个按钮,则只需单击一下即可。但是当我切换回按钮时,需要点击两次然后只需要一次,如果我再次切换回按钮,则会发生同样的事情 - 两次,一次...... 我想这与焦点有关。
如果我将ImageView
更改为ImageButton
,它会触发该功能两次,如果我添加if statemt (event.getAction() == MotionEvent.ACTION_DOWN)
,那么我必须再次点击该按钮两次..我想要按钮一直单击一次。我不明白为什么会发生这种情况,因为保存按钮一直只需点击一下..
编辑:如果我改变
image = imageArray[j];
到
image = imageArray[2];
然后按钮首先只需点击一下,但仍然无法得到它。
答案 0 :(得分:0)
我刚刚意识到我设置了ImageCount = 3,但是在数组中它从0开始计数,我在这个应用程序的开头编程了这个值,我认为它可能是错的。
答案 1 :(得分:-1)
你应该使用OnClickListener,
但也许是因为您没有告诉系统您已处理触摸事件。在处理触摸事件时尝试返回true,否则返回false。例如:
switch (v.getId()) {
case R.id.bBack:
if (j == 0) {
j = imageCount;
}
image = imageArray[j - 1];
rl.setBackgroundResource(image);
j = j - 1;
return true;
default:
return false;