单击 RadioGroup 失败

RadioGroup on click fails

我动态设置了一个广播组是这样的:

在我的 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();
}

关于设置用户

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 但我有以下问题:

  1. Whenever I click on the second RadioButton the first one cannot be clicked again

  2. the log on the selected listener doesn't log

我不知道哪里出了问题,因为 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);
        }
    });
}