Can't change background color of CheckBox view twice - Android

后端 未结 2 1950
北恋
北恋 2021-01-27 12:50

I try to change CheckBox background after user change its state to Checked. Code below doesn\'t work quite well. If i click unchecked checkbox

相关标签:
2条回答
  • 2021-01-27 13:52

    First some explanation of one unclear aspect

    Thing is that example colors mentioned in my code might be misleading if someone assume that i use android Color class. While i was using my versions of colors red and blue stored in color.xml and thats why I stated them in code as color.red instead of Color.RED.

    So my code as same as listener code in other answer, both are valid if you assume that color is taken from android class.

    Source of my problem is some strange glitch, or not known by me android behaviour that causes following code work faulty.

    public void handleCheckBoxClick(View view) {
        CheckBox tmpChkBox = (CheckBox) findViewById(view.getId());
        if(tmpChkBox.isChecked())
        {
            tmpChkBox.setBackgroundColor(color.blue);
        }
        else
        {
            tmpChkBox.setBackgroundColor(color.red);
        }
    }
    

    Precisely lines like this one

        tmpChkBox.setBackgroundColor([ColorFromResources]);
    

    While execution of code gave me just one occurence of color change, then it just stayed like that, completly unresponsive. That one change was largely misleading and got me stuck on this problem long time, and even made me leave it for later fixing. After some more research i figured that following change in code fixes my issue:

       tmpChkBox.setBackgroundColor(getResources().getColor([ColorFromResources]));
    

    Now all works like a charm. But I'm still puzzled why does call of color from resources works without getResources().getColor(...). Hopefully that answer will help someone as strangely stuck as me.

    0 讨论(0)
  • 2021-01-27 13:55

    For it to change when checked you need to attach an OnCheckChangedListener. Then place the above code inside that.

    CheckBox tmpChkBox = (CheckBox) findViewById(view.getId());
    tmpChkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                buttonView.setBackgroundColor(Color.BLUE);
            } else { 
                buttonView.setBackgroundColor(Color.RED);
            }
        }
     });
    
    0 讨论(0)
提交回复
热议问题