0

I had not used the tag element of views until just recently, and have since found a handful of cool uses. I have ran into an unusual problem that I hope someone can answer. This may be more general Java specific than Android, but I'm not sure. It has to do with how Java handles the Integer Class.

See these method bits. As it is, this works correctly. You can assume here POSITIVE and NEGATIVE are constants.

public void onClick(View v) {

    switch(v.getId()){

    case R.id.dialog_addrecord_button_sign:

        Sign mSign = (Sign) v.getTag();

        if(mSign.sign == NEGATIVE){
            ((Button) v).setText("+");
            mSign.sign = POSITIVE;
        } else {
            ((Button) v).setText("-");
            mSign.sign = NEGATIVE;
        }

        break;

    }

};


private void initButtons(){
    signButton = (Button) findViewById(R.id.dialog_addrecord_button_sign);
    signButton.setOnClickListener(this);
    signButton.setTag(new Sign());
}

private class Sign {

    int sign;

    private Sign(){
        sign = NEGATIVE;
    }

}

I realized, though, that I could just use the Integer class instead, rather than mull about with a custom class that only has a single field. I changed to this, however the button toggles only once, telling me that there is something I'm unaware of about how Java deals with the Integer class... can someone tell me why this does not work?

public void onClick(View v) {

    switch(v.getId()){

    case R.id.dialog_addrecord_button_sign:

        Integer sign = (Integer) v.getTag();

        if(sign == NEGATIVE){
            ((Button) v).setText("+");
            sign = POSITIVE;
        } else {
            ((Button) v).setText("-");
            sign = NEGATIVE;
        }

        break;

    }

};


private void initButtons(){
    signButton = (Button) findViewById(R.id.dialog_addrecord_button_sign);
    signButton.setOnClickListener(this);
    signButton.setTag(new Integer(NEGATIVE));
}
Maximus
  • 8,351
  • 3
  • 29
  • 37
  • I'm adding the Java tag back that was removed by an editor. The answer was particularly Java related. – Maximus Feb 14 '12 at 19:52

1 Answers1

1

You didn't post where POSITIVE and NEGATIVE are defined, but I guess you should check for equailty instead of object identity. The first answer to this question pretty much explains it.

In short: Use sign.equals(NEGATIVE) instead.

Community
  • 1
  • 1
wonderb0lt
  • 2,035
  • 1
  • 23
  • 37