Question

I am trying to dynamically add radiobuttons to radiogroups but the buttons never show up. The text does, though. I'm a beginner so please point out everything I've done wrong.

Using APKv7 (2.1 i think).

package test.test2;

import android.app.Activity;
import android.os.Bundle;
import android.widget.*;

public class TipsActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //setContentView(R.layout.main);


    //create objects
    ScrollView scrollv = new ScrollView(this);
    LinearLayout linlay = new LinearLayout(this);
    linlay.setOrientation(LinearLayout.VERTICAL);
    scrollv.addView(linlay);

    int currentQuestion = 0, questions = 3;
    int [] answers = new int[4];
    answers[0] = 3;
    answers[1] = 3;
    answers[2] = 4;
    answers[3] = 6;
    while (questions > currentQuestion) {           

        RadioGroup rg = new RadioGroup(this);

        TextView tv = new TextView(this);
        tv.setText("Question no. " + currentQuestion);



        int currentAnswer = 0;

        while (currentAnswer > answers[currentQuestion]) {

            RadioButton rb = new RadioButton(this);
            //rb.setText("Answer no. " + currentAnswer);
            rg.addView(rb);
            currentAnswer++;
        }

        linlay.addView(rg);
        linlay.addView(tv);
        currentQuestion++;  
    }
    setContentView(scrollv);
}
}

(notEnoughContext notEnoughContext)

Was it helpful?

Solution

I think you should do your while loop like this:

while (currentAnswer < answers[currentQuestion]) {

        RadioButton rb = new RadioButton(this);
        //rb.setText("Answer no. " + currentAnswer);
        rg.addView(rb);
        currentAnswer++;
    }

The problem is that currentAnswer is smaller than any answer...

OTHER TIPS

Replace this code:

int currentAnswer = 0;

while (currentAnswer > answers[currentQuestion])

To this:

int currentAnswer = 0;

while (currentAnswer < answers[currentQuestion])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top