我已成立了一个单选按钮组动态如下:
在我的XML,我有:
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/user_accounts_radios"
android:layout_gravity="left"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content"
android:orientation="vertical">
在我的Java代码,我有
RadioGroup radioGroup;
protected void onCreate(){
radioGroup = (RadioGroup) findViewById(R.id.user_accounts_radios);
setupUsers();
}
在setupUsers
void displayOpts(){
List<UserAccountDetailsModel> accounts = userAccountDetailsSqliteModel.getAccounts();
RadioGroup account_radios = new RadioGroup(this);
account_radios.setOrientation(LinearLayout.VERTICAL);
for (UserAccountDetailsModel user : accounts){
CompanyLocationsModel company = companyLocationSqliteModel.getCompany(user.getCompany_id());
RadioButton rdbtn = new RadioButton(this);
rdbtn.setTextSize(17);
rdbtn.setId(company.getId());
rdbtn.setText(user.getFirst_name() + " "+user.getLast_name() + " ---- " + company.getName());
account_radios.addView(rdbtn);
}
radioGroup.addView(account_radios);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
Log.i("test", "Checked is "+checkedId);
}
});
}
以上显示RadioGroup
但我有以下问题:
- 每当我点击第二
RadioButton
第一个不能再被点击- 所选择的听众日志不记录
我不知道什么是错的,因为RadioButtons
正确显示。
你正在创建你投入现有新RadioGroup
。这是错误的。只需使用现有的一个是这样的:
void displayOpts(){
List<UserAccountDetailsModel> accounts = userAccountDetailsSqliteModel.getAccounts();
//deleted line
//next line changed
radioGroup.setOrientation(LinearLayout.VERTICAL);
for (UserAccountDetailsModel user : accounts){
CompanyLocationsModel company = companyLocationSqliteModel.getCompany(user.getCompany_id());
RadioButton rdbtn = new RadioButton(this);
rdbtn.setTextSize(17);
rdbtn.setId(company.getId());
rdbtn.setText(user.getFirst_name() + " "+user.getLast_name() + " ---- " + company.getName());
//next line changed
radioGroup.addView(rdbtn);
}
//deleted line
//next line changed
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
Log.i("test", "Checked is "+checkedId);
}
});
}