Android OnTouchListener更改触摸项
我正在开发一个Android应用程序,其中我使用GridView绘制多个项目。为了绘制项目,我编写了一个适配器-Android OnTouchListener更改触摸项,android,gridview,ontouchlistener,notifydatasetchanged,Android,Gridview,Ontouchlistener,Notifydatasetchanged,我正在开发一个Android应用程序,其中我使用GridView绘制多个项目。为了绘制项目,我编写了一个适配器-ImageAdapter。每个图像都是一个整数,它是图像的资源,应该绘制在特定的位置上 我有自己按钮的图片(一个是“按钮打开”,一个是“按钮关闭”)。我想在按下按钮时将图像“button up”更新为“button down”。因此,我使用的是一个OnTouchListener 但是,当我在我的ImageAdapter中更新图像并调用方法notifyDataSetChanged(这是类
ImageAdapter
。每个图像都是一个整数,它是图像的资源,应该绘制在特定的位置上
我有自己按钮的图片(一个是“按钮打开”,一个是“按钮关闭”)。我想在按下按钮时将图像“button up”更新为“button down”。因此,我使用的是一个OnTouchListener
但是,当我在我的ImageAdapter
中更新图像并调用方法notifyDataSetChanged
(这是类BaseAdapter
的方法)时,当不再触摸按钮时,侦听器不会给我事件。这是因为设置了OnTouchListener
的资源被更改为新的图像“button down”
但是,如果我不调用notifyDataSetChanged(),一切都很好,但是按钮图像不会被更新
我的代码:
private void setTouchListenerForButtons(
Project project, final ImageAdapter imgadapt,
IConnection currentConnection, boolean editmode
) {
for(int i = 0; i < imgadapt.getCount(); i++) {
View v = project.getGui().getGridView().getChildAt(i);
try {
Object tag = v.getTag();
int p = 0;
if (tag != null) { // Button
p = (Integer) tag;
final int btnPosition = p;
project.getGui().getGridView().getChildAt(btnPosition).setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Toast.makeText(getContext(), event.getAction() + "", Toast.LENGTH_SHORT).show();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d(LOG_TAG, "Button down");
imgadapt.update(R.drawable.button_on, btnPosition);
imgadapt.notifyDataSetChanged(); // that's the PROBLEM
break;
case MotionEvent.ACTION_UP:
Log.d(LOG_TAG, "Button up");
imgadapt.update(R.drawable.button_off, btnPosition);
imgadapt.notifyDataSetChanged();
break;
}
return true;
}
});
}
} catch (NullPointerException e) {
}
}
}
private void setTouchListenerForButtons(
项目,最终图像适配器imgadapt,
I连接当前连接,布尔编辑模式
) {
对于(int i=0;i
如何解决此问题?在这种情况下,不要使用
setOnTouchListener
。创建选择器:
drawable/selector\u btn\u default.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_default_pressed"
android:state_pressed="true"/>
<item android:drawable="@drawable/btn_default"/>
</selector>
顺便说一句,在这种情况下调用
notifyDataSetChanged
是完全不好的。仅仅为了更改单个项目上的图像而刷新整个GridView是错误的。非常感谢,您的解决方案非常有效!!最后一个问题:根据按钮的状态,如何运行两种不同的方法?如果触摸图像,则应运行方法1,当不再触摸按钮时,应运行方法2。在这种情况下,您需要设置TouchListener,但您必须明智地处理事件,因为它将消耗事件,并会导致以下许多问题,例如,GridView可能无法滚动,等等,我已经知道了怎么做:
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/selector_btn_default"/>