Search code examples
blackberrytogglebuttonfield

Blackberry: How can I make a buttonfield act like toggle button?


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.


Solution

  • 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;
        }
    }