android gridview 按钮事件处理,Android初学者:触摸android gridview中的事件

我使用以下代码来处理gridview(从http://developer.android.com/resources/tutorials/views/hello-gridview.html稍微修改).我想用它们的“触摸”等价物替换onClicklistener和onClick()方法,即touchlistener和onTouch(),这样当我触摸gridview中的元素时,元素的图像会发生变化,并且同一个元素上的双击会接受它回到原始状态.

我该怎么做呢?我无法让我的代码执行此操作. clicklistener在某种程度上起作用,但触摸不是.请帮忙.

public class ImageAdapter extends BaseAdapter {

private Context mContext;

public ImageAdapter(Context c) {

mContext = c;

}

public int getCount() {

return mThumbIds.length;

}

public Object getItem(int position) {

return null;

}

public long getItemId(int position) {

return 0;

}

// create a new ImageView for each item referenced by the Adapter

public View getView(int position, View convertView, ViewGroup parent) {

ImageView imageView;

if (convertView == null) { // if it's not recycled, initialize some attributes

imageView = new ImageView(mContext);

imageView.setLayoutParams(new GridView.LayoutParams(85, 85));

imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

imageView.setPadding(8, 8, 8, 8);

imageView.setOnClickListener(new View.OnClickListener()

{

@Override

public void onClick(View view)

{

if(position==0)

{

//do this

}

else

{

//do this

}

}

});

} else {

imageView = (ImageView) convertView;

}

imageView.setImageResource(mThumbIds[position]);

return imageView;

}

// references to our images

private Integer[] mThumbIds = {

R.drawable.sample_2, R.drawable.sample_3,

R.drawable.sample_4, R.drawable.sample_5,

R.drawable.sample_6, R.drawable.sample_7,

R.drawable.sample_0, R.drawable.sample_1,

R.drawable.sample_2, R.drawable.sample_3,

R.drawable.sample_4, R.drawable.sample_5,

R.drawable.sample_6, R.drawable.sample_7,

R.drawable.sample_0, R.drawable.sample_1,

R.drawable.sample_2, R.drawable.sample_3,

R.drawable.sample_4, R.drawable.sample_5,

R.drawable.sample_6, R.drawable.sample_7

};

}

解决方法:

以这种方式使用OnTouchListener.阅读ACTION_UP,ACTION_MOVE和ACTION_DOWN之类的MotionEvent类型,这意味着在此处按下了键,移动了鼠标,或者在此处键入了键…

public void addListenerToGrid() {

gridView = (GridView) findViewById(R.id.gridView1);

gridView.setOnTouchListener(new OnTouchListener() {

public boolean onTouch(View v, MotionEvent me) {

int action = me.getActionMasked();

float currentXPosition = me.getX();

float currentYPosition = me.getY();

int position = gridView.pointToPosition((int) currentXPosition, (int) currentYPosition);

if (action == MotionEvent.ACTION_UP) {

// Key was pressed here

}

return true;

}

标签:onclick,touch,gridview,android,ontouchlistener

来源: https://codeday.me/bug/20190722/1498237.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值