Search code examples
javaandroidonclicklistenerandroid-togglebutton

Need to access properties of extended ToggleButton class through OnCheckChangedListener


I am trying to extend the ToggleButton class in a new class called TagToggleButton, whose sole difference is the fact that it has an ID that I can set associated with it. The TagToggleButton class looks as follows:

public class TagToggleButton extends ToggleButton {

    private long tagId;

    public TagToggleButton(Context context) {
        super(context);
    }

    public TagToggleButton(Context context, long id) {
        super(context);
        this.setTagId(id);
    }

    public void setTagId(long id) {
        this.tagId = id;
    }

    public long getTagId() {
        return this.tagId;
    }

}

I then want to call an OnClickListener that will allow me to get the ID property of the button. For instance:

tag.setOnCheckedChangeListener(new TagToggleButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            long id = buttonView.getTagId();
            // will do something with id afterwards
        } else {
            //Will do something else if the button isn't checked
        }
    }

However, I cannot call getTagId on buttonView as it is defined as a CompoundButton. How can I change buttonView to the type of TagToggleButton (that is, how do I override the OnCheckedChangeListener class within my TagToggleButton method?

Many thanks!


Solution

  • Inside the onCheckedChanged method cast the CompoundButton buttonView to TagToggleButton. To get the tag id you could do something like long id = ((TagToggleButton) buttonView).getTagId();