Android:如何获取用户选择的动态创建单选按钮的文本?

时间:2010-06-18 14:19:18

标签: android

如何检索动态创建的单选按钮的文本 用户选择?这是我的代码:

RadioGroup radiogroup = (RadioGroup) findViewById(R.id.rdbGp1); 
        // layout params to use when adding each radio button 
        LinearLayout.LayoutParams layoutParams = new 
RadioGroup.LayoutParams( 
                RadioGroup.LayoutParams.WRAP_CONTENT, 
                RadioGroup.LayoutParams.WRAP_CONTENT); 
 for (int i = 0; i < 4; i++){ 
            final RadioButton newRadioButton = new RadioButton(this); 
            c3 = db.getAns(3); 
        for (int j=0;j<i;j++) 
            c3.moveToNext(); 
           label = c3.getString(0); 
        newRadioButton.setText(label); 
        newRadioButton.setId(6); 
        radiogroup.addView(newRadioButton, layoutParams); 

等待回复, Maqsood

5 个答案:

答案 0 :(得分:17)

感到惊讶的是没有更简单的方法。如果您打算做一些特别的事情,但根据哪个按钮,您应该检查ID而不是标签。

radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
         void onCheckedChanged(RadioGroup rg, int checkedId) {
              for(int i=0; i<rg.getChildCount(); i++) {
                   RadioButton btn = (RadioButton) rg.getChildAt(i);
                   if(btn.getId() == checkedId) {
                        String text = btn.getText();
                        // do something with text
                        return;
                   }
              }
         }
    });

答案 1 :(得分:8)

我认为有一种更简单的方法可以做到这一点......

我刚刚创建了一个单选按钮,其中选中了按钮的ID,工作正常..

解决方案看起来像这样

RadioButton TheTextIsHere = (RadioButton) findViewById(RadioGroup.getCheckedRadioButtonId());

所以现在你有一个RadioButton引用RadioButton,它被检入RadioGroup,然后你就可以轻松......

TheTextIsHere.getText().toString();

希望我帮助过:)

答案 2 :(得分:3)

一个老问题,但这个答案可能对其他人有帮助。

我解决了问题,从而没有任何for循环从下面的RadioButton获取文本。 它适用于我,但我使用过xml,但认为原理无论如何都会有用。

//背后的代码仅在预先检查RadioButton时才有必要,因为如果没有选择RadioButton,则radioBtnChecked将为-1。因此,应用程序将“崩溃”,因为findviewbyid(-1)无效。 至少在xml中,您使用RadioButton预先检查android:checked="true"

RadioGroup radioGroup1 = (RadioGroup) findViewById(R.id.radiogroup1);
int radioBtnChecked = radioGroup1.getCheckedRadioButtonId();      
  // if (radioBtnChecked <= 0) {
  //   radioText = "None selected";      
  // } 
  // else {
       RadioButton rBtn = (RadioButton) findViewById(radioBtnChecked);
       radioText = rBtn.getText().toString();

答案 3 :(得分:0)

在这种情况下,HasMap更好。 HashMap旨在快速检索值...当然,您的特定情况使用“仅”4个单选按钮,因此您不会真正注意到差异。不过,我总是更喜欢这个解决方案

为HasMap创建一个成员变量:

Map<Integer, RadioButton> mapping = new HashMap<Integer, RadioButton>();

在创建RadioButtons的for循环中,将它们添加到hasmap:

{  
    ... // your for-loop
    int id = <your id here>
    newRadioButton.setId(id);        // set the id
    mapping.put(id, newRadioButton); // store the id as the key-value
    ... // continue with your for-loop
}

最后,在你的onCheckedChangeListener中,你可以从HashMap中提取RadioButton。注意:HashMap不会循环遍历所有条目以提取值,因此它会(稍微)更快。当然,在这种情况下你需要支付记忆费用:

radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(RadioGroup rg, int checkedId) 
    {
        String txt = ((RadioButton)mapping.get(checkedId)).getText();
        // do something with your text
    }
});

答案 4 :(得分:0)

有一种hacky方式可以做到这一点。 对于每个单选按钮,您需要将正整数作为ID。然后使用该ID,您可以参考所选的单选按钮。代码如下:

private void addButtons(String[] taskNames) {

    //You can define your radio group this way
    //or you can define it in onCreate. NOTE: if you 
    //define it in onCreate, make sure you do a 
    //rGroup.removeAllViews() or rGroup.removeView(child)
    rGroup = new RadioGroup(this);

    //hash code is the ID we will give to the radio buttons
    int hash;

    //going through the list of names and making radio buttons 
    //out of them and putting them into a radio group
    for(String name : taskNames)
    {
        //making a button
        RadioButton button = new RadioButton(this);

        //setting the button's text
        button.setText(name);

        //setting the button's ID by finding it's hashCode
        //Note that the ID MUST be a positive number
        hash = Math.abs((name).hashCode());
        button.setId(hash);

        //adding to the radio button group
        rGroup.addView(button);     
    }

    //Then you can add the radio group to your desired layout from the xml file
    LinearLayout desiredLayout = (LinearLayout) findViewById(R.id.desireLinearLayout);
    desiredLayout.addView(rGroup);
}

//here is a how to get the checked radio button
private void onClickSubmit()
{
    //for instance you can add the name to a DB
    DatabaseHandler db = new DatabaseHandler(this);
    try 
    {
        //get the ID of the button (i.e. the hashCode we assigned to it
        int id = rGroup.getCheckedRadioButtonId();

        //Getting the radio button
        RadioButton rbChecked = (RadioButton) rGroup.findViewById(id);

        //getting the name of the radio button
        String rbName = rbChecked.getText().toString();

        //adding the name to the DB 
        db.addName(rbName);

        //showing a friendly message to the user that the operation has been successful 
        Toast.makeText(this, "Yay, name added", Toast.LENGTH_SHORT).show();
    } 
    catch (Exception e) 
    {
        Toast.makeText(this, "Can't submit", Toast.LENGTH_SHORT).show();
    }
}

Hashcodes是确定性的,因此使用它们是安全的,但是由于我们正在使用Math.abs,因此我们为2个事物的可能性提供了一些空间,因为我们正在消除负面部分。但到目前为止,它对我来说一直很好。 但你可以做各种创造性的事情来避免碰撞。我相信你会弄明白的。)