How to create dynamic radiobuttons in CodenameOne

独自空忆成欢 提交于 2019-12-11 19:07:56

问题


Using CodenameOne, I created an array of RadioButtons based on the count of records on a database table.

Container searchDisplayContainer = findMyContainer(f);

for(int i=0; i < records.length; i++) {
    RadioButton rdb = new RadioButton();

    rdb.setName("rdb"+i);

    rdb.setText("rdb"+i);

    rdb.setGroup("locations"); 

    searchDisplayContainer.addComponent(rdb);
}

With this code, a number of RadioButtons are displayed on the simulator screen.

My problem is that after displaying the radiobuttons, I cannot check which one is selected.

Usually I can create the radiobutton in the theme.res and call it in the code with:

RadioButton rdb1 = findRadioButton(f);  

and check if the button is selected with if(rdb1.isSelected)

However since I am not creating my radio buttons initially in the theme.res, I cannot use the findRadioButton(f) method.

My question is how do I create a number of RadioButtons within the code and then be able to check if they are selected after the submit button is pressed?


Question Modification

package userclasses;

import generated.StateMachineBase;
import com.codename1.ui.*; 
import com.codename1.ui.events.*;
import com.codename1.ui.util.Resources;

/**
*
* @author Your name here
*/
public class StateMachine extends StateMachineBase {

    private Container searchDisplayContainer;
    private final int recordLength = 5;
    private ButtonGroup bg = new ButtonGroup();
    private RadioButton[] rdbs = new RadioButton[recordLength];

    public StateMachine(String resFile) {
        super(resFile);
    }

    /**
     * this method should be used to initialize variables instead of
     * the constructor/class scope to avoid race conditions
     */
    protected void initVars(Resources res) {
    }

    @Override
    protected void beforeMain(Form f) {
        searchDisplayContainer = findContainer1(f);

        for(int i=0;i<recordLength;i++){
            rdbs[i].setName("rdb"+i);
            rdbs[i].setText("rdb"+i);
            //add to button group
             bg.add(rdbs[i]);    
             //add to container
            searchDisplayContainer.addComponent(rdbs[i]);


        }
    }
    @Override
    protected void onMain_ButtonAction(Component c, ActionEvent event) {
        System.out.println(bg.getSelectedIndex());
    }
   }

回答1:


You need to create an instance of the ButtonGroup class and add the radio buttons to it in order to associate it to the other buttons in the group.



来源:https://stackoverflow.com/questions/22579554/how-to-create-dynamic-radiobuttons-in-codenameone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!