0

I have the following code:

scroll = (ScrollView) findViewById(R.id.scrollView1);
...
public void addItem(String str, int id) {
    LinearLayout lay = new LinearLayout(this);
    lay.setId(id);

    TextView txt = new TextView(this);
    txt.setText(str);

    lay.addView(txt);
    scroll.addView(lay);    
}

And when i call addItem() once it's Okay, but when i call it twice or more, like this:

addItem("text1",1);
addItem("text2",2);

my app crashes :(

1
  • show us the exception stack trace...it might help :) Commented May 28, 2012 at 16:43

1 Answer 1

1

It's because ScrollView can only host 1 direct child.

You could create a LinearLayout as the only child of the ScrollView, and then add to the LinearLayout instead of the ScrollView in your addItem method.

scroll = (ScrollView) findViewById(R.id.scrollView1);
LinearLayout lay = new LinearLayout(this);
scroll.addView(lay); 
// maybe do some more with lay here, or define it in xml instead of adding it here in the code
...
public void addItem(String str, int id) {
    LinearLayout lay2 = new LinearLayout(this);
    lay2.setId(id);

    TextView txt = new TextView(this);
    txt.setText(str);

    lay2.addView(txt);
    lay.addView(lay2);    
}
Sign up to request clarification or add additional context in comments.

2 Comments

@eightx2 what is the need of lay2 in addItem method can't i directly add view to the lay...like lay.addView(txt); instead of adding text to a layout and then adding that layout the actual layout??
@Archie.bpgc Yes that's right, you can do that. I just edited his code directly, that's the only reason lay2 is there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.