在runTime android上添加多个TextView

时间:2014-07-06 07:38:03

标签: android view runtime

我试图在运行时将多个TextView添加到relativeLayout。 原因是要根据用户的选择创建列表。

我知道如何添加1个textView。但当我将代码输入循环并试图创建超过1时,它只是没有显示任何内容..

请求帮助,

 int left=70,top=25;
 for (String s:startLetterPos){
        params.leftMargin = left;
        top += 70;
        params.topMargin = top;
        TextView tv = new TextView(this);
        tv.setLayoutParams(params);
        tv.setText(s);
        tv.setVisibility(View.VISIBLE);
        tv.setTextSize(20);

        testLayout.addView(tv);

    }

编辑:活动的完整代码:

package com.fgdvir.psychowords;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class WordTest extends Activity {
    RelativeLayout testLayout;
    int            displayWidth, displayHeight;
    ArrayList<String> startLetterPos = new ArrayList<String>();
    //private int[] startLetterPos = new int[26];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.word_test);

    startLetterPos = getIntent().getStringArrayListExtra("test");

    testLayout = (RelativeLayout) findViewById(R.id.word_test);
    create_questions();
    // Get Screen size
    /*
     * Display display = getWindowManager().getDefaultDisplay(); Point size = new `      `Point(); display.getSize(size);
     * displayWidth = size.x; displayHeight = size.y;
     */

}

public void create_questions() {
    int left=70,top=25;
    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT
            , LayoutParams.WRAP_CONTENT);
    for (String s:startLetterPos){
        params.leftMargin = left;
        top += 70;
        params.topMargin = top;
        TextView tv = new TextView(this);
        tv.setLayoutParams(params);
        tv.setText(s);
        tv.setVisibility(View.VISIBLE);
        tv.setTextSize(20);

        testLayout.addView(tv);

    }

}

}

1 个答案:

答案 0 :(得分:0)

所以我明白了 我仍然不知道为什么这不起作用,但我找到了另一种方法。 我将文本添加到linearLayout,然后将linearLayout添加到我的相对布局:

LinearLayout lL = new LinearLayout(this);
    lL.setOrientation(LinearLayout.VERTICAL);
    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT
            , LayoutParams.WRAP_CONTENT);
    for (int i = 0; i<26; i++){
        String s = startLetterPos.get(i);
        TextView tv = new TextView(this);
        tv.setId(i);
        tv.setText(s);
        tv.setTextColor(Color.WHITE);
        tv.setTextSize(20);
        if (i != 0 ){
        params.addRule(RelativeLayout.BELOW, i-1);
        }

        lL.addView(tv,params);

    }
    testLayout.addView(lL);

}