Create a new TextView programmatically then display it below another TextView

Lope Emano picture Lope Emano · Dec 9, 2010 · Viewed 179k times · Source
String[] textArray={"one","two","asdasasdf asdf dsdaa"};
int length=textArray.length;
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
for(int i=0;i<length;i++){
    TextView tv=new TextView(getApplicationContext());
    tv.setText(textArray[i]);
    relativeParams.addRule(RelativeLayout.BELOW, tv.getId());
    layout.addView(tv, relativeParams);
}

I need to do something like that.. so it would display as

one
two
asdfasdfsomething

on the screen..

Answer

WeNeigh picture WeNeigh · Jan 17, 2011

If it's not important to use a RelativeLayout, you could use a LinearLayout, and do this:

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);

Doing this allows you to avoid the addRule method you've tried. You can simply use addView() to add new TextViews.

Complete code:

String[] textArray = {"One", "Two", "Three", "Four"};
LinearLayout linearLayout = new LinearLayout(this);
setContentView(linearLayout);
linearLayout.setOrientation(LinearLayout.VERTICAL);        
for( int i = 0; i < textArray.length; i++ )
{
    TextView textView = new TextView(this);
    textView.setText(textArray[i]);
    linearLayout.addView(textView);
}