简体   繁体   中英

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?

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);
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM