How can we create dynamic textview?

前端 未结 6 1729
故里飘歌
故里飘歌 2021-01-21 20:13

how to create the textview in code not in xml file. It is because number of textviews will be changing in my application according to some integer.

6条回答
  •  甜味超标
    2021-01-21 20:55

    Something like the following should be what you need:

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

提交回复
热议问题