I am trying to repeat an action while a button is pressed.
I have already searched for some solutions and all are useless. My assumption is that this may happen because my button
s are inside a ListView
item.
What I want to approach the following application:
Where I can increment (+1) or decrement(-1) the value of each EditText
(Count) by single time pressing, or holding pressed the button for a while.
My adapter code:
public class ItemAdapter extends ArrayAdapter<SizeCount> {
private Collection<SizeCount> list;
private static final String LOG_TAG = "MemoListAdapter";
EditText tbCount;
TextView tvSize;
Button btAdd, btSubstract;
public ItemAdapter (Context context,List<SizeCount> list){
super(context,0,list);
this.list = list;
}
public Collection<SizeCount> getList() {
return list;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
View v = convertView;
if(v == null){
v = LayoutInflater.from(getContext()).inflate(
R.layout.entry_size_count,parent,false
);
}
final SizeCount item = getItem(position);
tvSize = (TextView) v.findViewById(R.id.tvSize);
tvSize.setFocusable(false);
tbCount= (EditText) v.findViewById(R.id.tbCount);
tvSize .setText(item.getArticles().getSize());
tbCount.setText(item.getCount()+"");
btAdd= v.findViewById(R.id.btAdd);
btAdd.setOnTouchListener(new View.OnTouchListener() {
private Handler mHandler;
@Override public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mHandler != null) return true;
mHandler = new Handler();
mHandler.postDelayed(mAction, 500);
break;
case MotionEvent.ACTION_UP:
if (mHandler == null) return true;
mHandler.removeCallbacks(mAction);
mHandler = null;
break;
}
return false;
}
Runnable mAction = new Runnable() {
@Override public void run() {
float currentCount = item.getCount();
float nextCount = currentCount + 1;
item.setCount(nextCount);
item.setModified(true);
notifyDataSetChanged();
mHandler.postDelayed(this, 500);
}
};
});
return v;
} catch (Exception ex) {
Log.e(LOG_TAG, "error", ex);
return null;
}
}
}
And the behaviour I get:
- When I click the (+)
button
a single time: Nothing changes. - When I hold pressed the (+)
button
: It starts increasing and never stops. Even when I release it.