Android: Как получить текст динамически созданной радиокнопки, выбранной пользователем? - PullRequest
4 голосов
/ 18 июня 2010

Как я могу получить текст динамически созданного переключателя, выбранного пользователем?Вот мой код:

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); 

Жду ответа, Максуд

Ответы [ 5 ]

17 голосов
/ 18 июня 2010

Удивлен, что нет более легкого пути. Если вы собираетесь сделать что-то особенное, основываясь на том, какую кнопку вам, вероятно, следует проверить идентификатор вместо метки.

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;
                   }
              }
         }
    });
8 голосов
/ 24 августа 2011

Я думаю, что есть более простой способ сделать это ...

Я только что создал переключатель с проверенным идентификатором кнопки и работает нормально ..

Решение выглядит так

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

Итак, теперь у вас есть RadioButton, который ссылается на RadioButton, который зарегистрирован в RadioGroup, и вы можете легко ...

TheTextIsHere.getText().toString();

Надеюсь, я помог:)

3 голосов
/ 09 декабря 2011

Старый вопрос, но этот ответ, возможно, может помочь кому-то еще.

Я решил проблему, чтобы получить текст из RadioButton, как показано ниже, без какого-либо цикла for.Это работает для меня, но я использовал xml, но думаю, что принцип будет работать в любом случае.

Код позади // необходим, только если нет RadioButton предварительной проверки, потому что radioBtnChecked будет -1, еслиRadioButton не выбрано.Таким образом, приложение "вылетает", потому что 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();
0 голосов
/ 04 января 2014

Есть хакерский способ сделать это.Для каждого переключателя вам нужно иметь положительное целое число в качестве идентификатора.Затем, используя этот идентификатор, вы можете обратиться к выбранному переключателю.Вот код:

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

Хеш-коды являются детерминированными, поэтому их безопасно использовать, но, поскольку мы создаем Math.abs, мы оставляем место для возможностей хеширования двух вещей с одинаковым значением, потому чтоустранение отрицательной части.Но пока у меня все работает нормально.Но вы можете делать все что угодно, чтобы избежать столкновений.Я уверен, что вы поймете это:)

0 голосов
/ 09 декабря 2011

HasMap лучше в такой ситуации. HashMap разработаны для быстрого извлечения значений ... Конечно, в вашем конкретном случае используются только 4 переключателя, поэтому вы не заметите разницу. Тем не менее, я бы всегда предпочел это решение

Создать переменную-член для HasMap:

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

В цикле for, где вы создаете свои RadioButtons, добавьте их в 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 вы можете извлечь RadioButton из HashMap. Примечание: 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
    }
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...