我正在关注本教程,但我正在尝试为每个图像添加“触摸”方面。
如您所见,HelloGridView
与教程完全相同:
public class HelloGridView extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
对于ImageAdapter
,我添加了一个onTouchListener
:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// create a new ImageView for each item referenced by the Adapter
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(300, 300));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
imageView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
Log.v("log_tag", "MotionEvent.ACTION_DOWN");
return true;
} else if(event.getAction()==MotionEvent.ACTION_UP){
Toast.makeText(mContext, "ACTION_UP", Toast.LENGTH_SHORT).show();
Log.v("log_tag", "MotionEvent.ACTION_UP");
return false;
} else {
return false;
}
}
});
return imageView;
}
}
问题是,每当我触摸其中一张图像时, 中的onTouchListener
火ImageAdapter
,而不是onItemClickListener
中的火HelloGridView
。
我想onItemClickListener
开火,因此如果事件是,则ACTION_UP
返回 false,如果是,则返回 true 。MotionEvent.ACTION_UP
MotionEvent.ACTION_DOWN
据我了解,如果我返回 true,则onTouchListener
消耗事件并完成。但是,如果我返回 false,则onTouchListener
不会消耗该事件,而是将其传递给onItemClickListener
in HelloGridView
。
不幸的是,只有HelloGridView
当我在事件为ACTION_DOWN
. 但是,当我这样做时,ACTION_UP
永远不会被执行。有人可以告诉我我做错了什么以及如何解决吗?如果我的问题不清楚,请告诉我,我会尽力澄清!:)