-1
public void onClick(View v) {
        if (v == b1) {
            b1.setBackgroundColor(Color.WHITE);
            delay(300);
            b1.setBackgroundColor(Color.GREEN);
        }

//-------------------------------------------------------------- /** * @param ms time of delay */

public void delay(int ms) {
    checkDelayArgument(ms);
    Thread thread = Thread.currentThread();
    if (!thread.isInterrupted()) {
        try {
            Thread.sleep(ms);
        } catch (final InterruptedException ignored) {
            thread.interrupt(); // Preserve interrupt status
        }
    }
}

/**
 * @param ms time of delay
 */

private static void checkDelayArgument(int ms) {
    if (ms < 0 || ms > 60000) {
        throw new IllegalArgumentException("Delay must be to 0 to 60,000ms");
    }
}
//--------------------------------------------------------------

Result: Only green color change and i don't see the change of white color

1 Answers1

0

Your delay method isn't great, it will block the UI thread.

Try something like this:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
   public void run() {
      runOnUiThread() {
         b1.setBackgroundColor(Color.GREEN);
      }
   }, 300);

but even then that is wonky. What you really want is an Animation instead of this. Or an AnimationSet.

Try something like this, it might set you on the right path.

    public static Animator backgroundColorChangeAnimation(final View targetView, int startColor, int endColor, long duration) {
        ArgbEvaluator evaluator = new ArgbEvaluator();
        ValueAnimator animator = new ValueAnimator();
        animator.setIntValues(startColor, endColor);
        animator.setEvaluator(evaluator);
        animator.setDuration(duration);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int color = (int) animation.getAnimatedValue();
                targetView.setBackgroundColor(color);
            }
        });
        animator.start();

        return animator;
    }

and use it like this:

        currentAnim = AnimUtils.backgroundColorChangeAnimation(
                selectedTextView,
                getResources().getColor(R.color.white),
                getResources().getColor(R.color.green),
                300
        );

that will immediatelly run the animator, which will start out at white color and end up in green.

more info is required to hit the nail (of your question) on the head, but you certainly don't want to delay things by calling Thread.sleep().

Shark
  • 6,513
  • 3
  • 28
  • 50