以编程方式更改可绘制onClick的按钮背景 [英] Programmatically change button background drawable onClick

查看:97
本文介绍了以编程方式更改可绘制onClick的按钮背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图切换按钮的背景可绘制对象,以便当用户单击按钮时其背景被更改,并且当用户再次单击按钮时其背景恢复为默认.这是我的代码:

I am trying to toggle my button's background drawables, so that when the user clicks the button its background is changed and when the user clicks the button again its background returns to defaul. Here is my code:

public void Favorites(View V) {
  Button star = (Button) findViewById(R.id.buttonStar);
  if(star.getBackground().equals(R.drawable.btn_star_off)) {
    star.setBackgroundResource(R.drawable.btn_star_on);
  } else {               
    star.setBackgroundResource(R.drawable.btn_star_off);
  }
}

我很确定这不是您将if语句一起使用的方式.有人可以建议一种方法吗?

I am pretty sure this is not how you use drawables with if statements. Can someone suggest a way to do it?

推荐答案

private boolean isButtonClicked = false; // You should add a boolean flag to record the button on/off state

protected void onCreate(Bundle savedInstanceState) {
    ......
    Button star = (Button) findViewById(R.id.buttonStar);
    star.setOnClickListener(new OnClickListener() { // Then you should add add click listener for your button.
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.buttonStar) {
                isButtonClicked = !isButtonClicked; // toggle the boolean flag
                v.setBackgroundResource(isButtonClicked ? R.drawable.btn_star_on : R.drawable.btn_star_off);
            }
        }
    });
}

这篇关于以编程方式更改可绘制onClick的按钮背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆