views:

153

answers:

1

I have a single button which I want to use as Start/Stop button. How can I make the buttonfield work as toggle button?

Please help.

+4  A: 

Just change button label on fieldChange or navigationClick or touchEvent, don't forget to save toggle state in class member:

class ToggleButtonField extends ButtonField {
    int mToggleState = -1;
    String[] mLabels = {};
    public ToggleButtonField(String[] labels) {
        super(CONSUME_CLICK);
        if(labels != null && labels.length > 0)
        {
            mLabels = labels;
            mToggleState = 0;
            updateLabel();                  
        }       
    }

    private void updateLabel() {
        setLabel(mLabels[mToggleState]);        
    }

    protected void fieldChangeNotify(int context) {
        mToggleState = getNextToggleState(mToggleState);
        updateLabel();
        super.fieldChangeNotify(context);
    }

    private int getNextToggleState(int state) {
        int result = mToggleState+1;
        if(result >= mLabels.length)
            result = 0;
        return result;
    }
}
Max Gontar