java – 以编程方式创建一个新的TextView,然后在另一个TextView下面显示它

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

我需要做这样的事情,所以它会显示为

one
two
asdfasdfsomething

屏幕上..

如果使用RelativeLayout不重要,您可以使用LinearLayout,并执行以下操作:

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

这样做可以避免您尝试的addRule方法。你可以简单地使用addView()来添加新的TextViews。

完整代码:

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);
}
http://stackoverflow.com/questions/4394293/create-a-new-textview-programmatically-then-display-it-below-another-textview

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – 以编程方式创建一个新的TextView,然后在另一个TextView下面显示它