繁体   English   中英

如何将动态加载的单选按钮放入一个组中?

[英]How do you put dynamically loaded radio buttons into a group?

单选按钮应该是互斥的。 但他们需要在一个“广播组”中。

根据文档,“通过将它们组合在一起,系统可以确保一次只能选择一个单选按钮。”

我制作了一些单选按钮(动态加载),并确保将它们放在一个组中。 但是,它们并不是相互排斥的,我可以一次检查所有这些。

我该如何解决?

这是代码:

public class MainActivity extends AppCompatActivity {

    private LinearLayout candidatesLayout;
    private String[] candidates = {"Smith","Johnson","Williams","Brown","Jones","Garcia","Miller","Davis","Rodriguez","Martinez"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        candidatesLayout = (LinearLayout) findViewById(R.id.candidatesLayout);

        final int N = candidates.length; // total number of textviews to add
        final TextView[] myTextViews = new TextView[N]; // create an empty array;

        for (int i = 0; i < N; i++) {
            // create a new textview
            final TextView rowTextView = new TextView(this); //rowTextView is persons name
            //create horizonal parent for radio buttons
            LinearLayout radioButtons = new LinearLayout(this);
            LinearLayout numbers = new LinearLayout(this);
            radioButtons.setOrientation(LinearLayout.HORIZONTAL);
            //create new radio buttons
            final RadioGroup radioGroup = new RadioGroup(this);
            RadioButton button;
            for(int ii = 0; ii < N; ii++) {
                button = new RadioButton(this); //I should not be able to click more than one of these!
                radioButtons.addView(button);
            }
            candidatesLayout.addView(rowTextView);
            candidatesLayout.addView(radioButtons);
          }

    }
}

我猜他们并不真正属于我认为他们所在的群体。

您已创建RadioGroup ,但未将其添加到布局中。 因此,将添加的单选按钮替换为以下代码段:

 for (int i = 0; i < N; i++) {
    // create a new textview
    final TextView rowTextView = new TextView(this); //rowTextView is persons name
    //create horizonal parent for radio buttons
    LinearLayout radioButtons = new LinearLayout(this);
    LinearLayout numbers = new LinearLayout(this);
    radioButtons.setOrientation(LinearLayout.HORIZONTAL);
    //create new radio buttons
    final RadioGroup radioGroup = new RadioGroup(this);
    RadioButton button;
    for(int ii = 0; ii < N; ii++) {
        button = new RadioButton(this); 
        radioGroup.addView(button);  // <-- Add to Group
    }
    candidatesLayout.addView(rowTextView);
    candidatesLayout.addView(radioGroup);  // Add Group itself
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM