2

如何在不在 xml 文件中的代码中创建文本视图。这是因为我的应用程序中的文本视图数量将根据某个整数发生变化。

4

6 回答 6

4

这是动态创建 TextView 的代码

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

for (int i = 0; i < 3; i++) {

TextView dynamicTextView = new TextView(this);
dynamicTextView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT));
        dynamicTextView.setText("NewYork");
        layout.addView(tstate);

}
于 2012-05-07T12:35:24.780 回答
1

也许这就是你需要的:

LinearLayout lin = (LinearLayout) findViewById(R.id.myLinear);

  for (int i = 0; i <= 10 ; i++)
  {
      TextView myText = new TextView(this);
      myText.setText("textview# "+ i);
      lin.addView(myText);
  }
于 2012-05-07T12:39:06.640 回答
0

您需要以下内容:

final int N = 10; // total number of textviews to add

final TextView[] myTextViews = new TextView[N]; // create an empty array;

for (int i = 0; i < N; i++) {
    // create a new textview
    final TextView rowTextView = new TextView(this);

    // set some properties of rowTextView or something
    rowTextView.setText("This is TextView #" + i);

    // add the textview to the linearlayout
    myLinearLayout.addView(rowTextView);

    // save a reference to the textview for later
    myTextViews[i] = rowTextView;
}
于 2012-05-07T12:33:40.630 回答
0
private LinearLayout ll;
private TextView tv;


      // in oncreate()
onCreate()
{
        int WrapWidth = LinearLayout.LayoutParams.WRAP_CONTENT;
        int WrapHeight = LinearLayout.LayoutParams.WRAP_CONTENT;

        tv = new TextView(this);

        ll.addView(tv,WrapWidth,WrapHeight);


}
于 2012-05-07T12:36:15.543 回答
0

代码在这里

final int c = 12;
final TextView[] mtext = new TextView[c]; 
for (int i = 0; i < c; i++) {
TextView rowtxt = new TextView(this);
rowtxt.setText("Hello" + i);
myLinearLayout.addView(rowtxt);
myTextViews[i] = rowtxt;
myTextViews[i].setOnClickListener(onclicklistener);//textview click

}

OnClickListeners 代码在这里

OnClickListener onclicklistener = new OnClickListener() {

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    if(v == myTextViews[0]){
        //do whatever you want....
    }
}

};

希望对你有帮助

于 2016-09-02T10:50:00.430 回答
0

你用TextView textView = new TextView(CurrentActivity.this);

然后添加TextView类附带的 setter 参数

于 2017-06-12T06:57:38.083 回答