Question

I need to add some strings to my layout, but I need to add each string in a new line (as a list) and make the layout scrollable when it exceeds the vertical dimension. The amount of these strings is defined at runtime so I do like this:

ScrollView scrollView = new ScrollView(context);
LinearLayout scrollViewLayout = new LinearLayout(context);
scrollViewLayout.setOrientation(LinearLayout.VERTICAL);
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,
                                             LayoutParams.WRAP_CONTENT);
TextView tv2;

for(int i = 0; i < count; i++) { //count is defined at runtime when the
                                 //array strings[] is created
                                 //and defines the amount of array's values
    tv2 = new TextView(context);
    tv2.setLayoutParams(layoutParams);
    tv2.setText(strings[i]);
    scrollViewLayout.addView(tv2);
}

scrollView.addView(scrollViewLayout);

But I don't think that instantiating objects in a loop and adding strings like this is acceptable, moreover, I get log messages "GC_FOR_ALLOC..." and "Grow heap..." because of that ScrollView object so I think I should perform this action in another, more appropriate way. Please explain me how to correctly add strings to a layout and make it scrollable. Thanks in advance!

Was it helpful?

Solution 2

Why not just use one TextView and append text to it in each loop iteration. Something like

TextView tv2;
tv2 = new TextView(context);
tv2.setLayoutParams(layoutParams);
for(int i = 0; i < count; i++) { //count is defined at runtime when the
                             //array strings[] is created
                             //and defines the amount of array's values
    if (i > 0)
        tv2.append(" \n" + strings[i]);
    else
        tv2.setText(strings[i]);
}
scrollView.addView(scrollViewLayout);

OTHER TIPS

Any reason why you can't use the same TextView again and again?

For example:

tv2.setText(tv2.getText() + *newline* + msg);

In your case:

for(String str : strings)
{
     tv2.setText(tv2.getText() + *newline* + str);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top