I am developing an Android app, in which I use a GridView to draw multiple items. For drawing the items I've written an adapter - ImageAdapter
. Every image is an integer number, which is the resource of the image which should be drawn on the specific position.
I have images for my own button (one image for "button up", and one for "button down"). I want to update the image "button up" to "button down" while the button is touched. Therefore I am using an OnTouchListener
.
However when I update the image in my ImageAdapter
and call the method notifyDataSetChanged
(which is a method of the class BaseAdapter
) the listener doesn't give me the event when the button isn't touched any more. That's because the resource to which the OnTouchListener
was set was changed to the new image "button down".
However, if I do not call notifyDataSetChanged()
, everything is great, but then the button image is not going to be updated.
My code:
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) {
}
}
}
How can I resolve this problem?