如何更改 android 中按钮的背景并在几秒钟后保留它

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

我提到了这个 -->

我试过上面的解决方案,但它不起作用 --> 有几秒钟没有显示该可绘制对象

这是我的代码:

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

连吐司都无法点击

我错过了什么?

这对我来说很好,你需要将视图设置为最终视图,这样你就可以在处理程序主体中访问它

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