[英]How to create dynamic radiobuttons in CodenameOne
使用CodenameOne,我根據數據庫表上的記錄數創建了一個RadioButtons數組。
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);
}
使用此代碼,模擬器屏幕上將顯示許多RadioButtons。
我的問題是顯示單選按鈕后,我無法檢查選擇了哪個。
通常,我可以在theme.res中創建單選按鈕,並使用以下代碼在代碼中調用它:
RadioButton rdb1 = findRadioButton(f);
並檢查是否通過if(rdb1.isSelected)選擇了按鈕
但是,由於我最初不是在theme.res中創建單選按鈕,因此無法使用findRadioButton(f)
方法。
我的問題是如何在代碼中創建多個RadioButton,然后在按下“提交”按鈕后檢查是否選中了它們?
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());
}
}
您需要創建ButtonGroup
類的實例,並向其中添加單選按鈕,以便將其與組中的其他按鈕相關聯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.