I have Button
and an TextView
. Initially on click of button i an incrementing the count value and display in the TextView. The code i have used to do so is.
buttonDayPlus.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
count = count + 1;
textView.setText(Integer.toString(count));
}
}
But now what i want is if the user pressed the Button, then i want to increment the value one after another and display the increment value in the textView
and as soon as user move his hand up...the final increment value is shown in textView
. So if anyone knows help me to solve this out
You will need to use a Handler object because you have to implement a separate thread for incrementing/decrementing
public class MainActivity extends Activity {
private boolean autoIncrement = false;
private boolean autoDecrement = false;
private final long REPEAT_DELAY = 50;
private Handler repeatUpdateHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input);
class RepetitiveUpdater implements Runnable {
@Override
public void run() {
if (autoIncrement) {
increment();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
} else if (autoDecrement) {
decrement();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
}
}
}
up.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
increment();
}
});
up.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
autoIncrement = true;
repeatUpdateHandler.post(new RepetitiveUpdater());
return false;
}
});
up.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP && autoIncrement) {
autoIncrement = false;
}
return false;
}
});
}
public void increment() {
if (i < 100) {
i++;
TextView no = (TextView) findViewById(R.id.no);
no.setText(String.valueOf(i));
}
}
}
Do the same for decrement.
Courtesy: Github, author: Jeffrey F. Cole
I just answered this question here https://stackoverflow.com/a/41466381/2991628
I created a CounterHandler
class to do all the counting and event handling. This is how it works.
new CounterHandler.Builder()
.incrementalView(buttonPlus)
.decrementalView(buttonMinus)
.minRange(-50) // cant go any less than -50
.maxRange(50) // cant go any further than 50
.isCycle(true) // 49,50,-50,-49 and so on
.counterDelay(200) // speed of counter
.counterStep(2) // steps e.g. 0,2,4,6...
.listener(this) // to listen counter results and show them in app
.build();
You can find this class from my gist https://gist.github.com/nomanr/d142f4ccaf55ceba22e7f7122b55b9b6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With