Search code examples
androidandroid-layoutkotlinbuttonhandler

How to change background of a button in android and retain it after few seconds


I referred this --> https://stackoverflow.com/a/31367723/12553303

I tried above solution but it is not working --> not displaying that drawable for few second

here is my code:

   buynow.setOnClickListener(object : View.OnClickListener{
        override fun onClick(v: View?) {
            // set the color red first.
   buynow.setBackgroundResource(R.drawable.mybuttonred)
            // change to original after 5 secs.
            Handler().postDelayed(Runnable { buynow.setBackgroundResource(R.drawable.mybutton)
                Toast.makeText(applicationContext,"ksjdf",Toast.LENGTH_LONG).show()
            },
                5000)
        }
    })

Even the toast is not working on click

what I am missing?


Solution

  • This works fine with me you need to make view final so you can access it inside handler body

    buyNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                view.setBackgroundColor(Color.RED); //set the color to red
                // Delay of 2 seconds (200 ms) before changing back the color to black
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        view.setBackgroundColor(Color.BLACK); //set the color to black
                    }
                }, 200);
            }
        });