以编程方式创build一个新的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); } 
 public View recentView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Create a relative layout and add a button relativeLayout = new RelativeLayout(this); btn = new Button(this); btn.setId((int)System.currentTimeMillis()); recentView = btn; btn.setText("Click me"); relativeLayout.addView(btn); setContentView(relativeLayout); btn.setOnClickListener(new View.OnClickListener() { @Overr ide public void onClick(View view) { //Create a textView, set a random ID and position it below the most recently added view textView = new TextView(ActivityName.this); textView.setId((int)System.currentTimeMillis()); layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); layoutParams.addRule(RelativeLayout.BELOW, recentView.getId()); textView.setText("Time: "+System.currentTimeMillis()); relativeLayout.addView(textView, layoutParams); recentView = textView; } }); } 

这可以被修改,以在不同的TextView中显示一个String数组的每个元素。

试试这个代码:

 final String[] str = {"one","two","three","asdfgf"}; final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl); final TextView[] tv = new TextView[10]; for (int i=0; i<str.length; i++) { tv[i] = new TextView(this); RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams ((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT); params.leftMargin = 50; params.topMargin = i*50; tv[i].setText(str[i]); tv[i].setTextSize((float) 20); tv[i].setPadding(20, 50, 20, 50); tv[i].setLayoutParams(params); rl.addView(tv[i]); } 

你不是给文本视图分配任何id,而是使用tv.getId()把它作为parameter passing给addRule方法。 尝试通过tv.setId(int)设置一个唯一的ID。

您也可以使用垂直方向的LinearLayout,实际上可能会更容易。 否则,如果不需要,我更喜欢使用RelativeLayouts的LinearLayout。