将textViews动态添加到linearLayout

Ant*_*ano 30 android add dynamic textview android-edittext

我在这里读到这个,我完全失去了它,但可以使用一些帮助.

我的应用程序将列名称从sqlite拉入数组.我想创建一个textview并为每个文本编辑文本(通过数组的大小),我记得在某处你可以将textViews变量名称视为数组,但我不知道它现在在哪里.

那么,如果有多个列表在数组中,我将如何动态创建textView和editText?

它就像是

TextView tv[] = new TextView()...

for(...){
tv[i]...
}
Run Code Online (Sandbox Code Playgroud)

这是正确的吗?

我感谢您的帮助!

Jos*_*arl 68

以下内容应该是您所需要的:

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 row #" + i);

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

    // save a reference to the textview for later
    myTextViews[i] = rowTextView;
}
Run Code Online (Sandbox Code Playgroud)


小智 13

您可以TextView通过以下代码在运行时添加s:

LinearLayout lLayout = (LinearLayout) findViewById(R.id.linearlayout2); // Root ViewGroup in which you want to add textviews
for (int i = 0; i < 5; i++) {
    TextView tv = new TextView(this); // Prepare textview object programmatically
    tv.setText("Dynamic TextView" + i);
    tv.setId(i + 5);
    lLayout.addView(tv); // Add to your ViewGroup using this method
}
Run Code Online (Sandbox Code Playgroud)

  • 如何将`OnClickListeners`绑定到创建的元素? (3认同)