在android中动态添加TextView

时间:2013-12-25 11:26:42

标签: android

我想创建一个文本字段并输入以下“ANDROID,IPHONE,BLACKBERRY,WINDOWS”。单击SUBMIT按钮显示不同文本视图中的每个字符串。这是我的代码

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        b = (Button) findViewById (R.id.button1);
        b.setOnClickListener(this);

    }
public void onClick(View v) {
        // TODO Auto-generated method stub
        et = (EditText) findViewById (R.id.etext);
         texts = et.getText().toString();

        tv = (TextView) findViewById (R.id.textView1);
        tv.setText(texts);
}

2 个答案:

答案 0 :(得分:0)

split围绕comma的字符串。

for loop中直到分割数组的长度,创建新的TextView并将其作为子项附加到父布局(设置适当的ID)

类似这样的事情

LinearLayout layout = (LinearLayout) findViewById(R.id.parentLayout);

String[] items = data.split(",");
for (String item : items)
{

    TextView valueTV = new TextView(this);
    valueTV.setText(item);
    valueTV.setId("textView"+i);
    valueTV.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));

    layout.addView(valueTV);
}

答案 1 :(得分:0)

使用以下代码

public void onClick(View v) {

View parent;  //parent view where to add
ViewGroup layout=new LinearLayout(context);
layout.setLayoutParams(new   ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

TextView tv1=new TextView(context);
tv1.setText("Android");
TextView tv2=new TextView(context);
tv2.setText("Blackberry");
TextView tv3=new TextView(context);
tv3.setText("Windows");
TextView tv4=new TextView(context);
tv4.setText("iphone");

 layout.addView(tv1);
 layout.addView(tv2);
 layout.addView(tv3);
 layout.addView(tv4);

parent.addView(layout);

}