在 Android Studio 中使用 while 循环显示带有 textview 对象的数据

Using while loop in Android Studio to display data with textview objects

所以我在 Android 工作室工作,使用 Java 作为我的语言,并且我有一个嵌入式数据库。我想按我的应用程序上的某个按钮来显示当时数据库中的所有内容。假设我的数据库包含字母数字组合,例如“A,45”、“B,57”等

现在要在我的应用程序中显示此数据,我使用以下方法:

LinearLayout my_layout = (LinearLayout)findViewById(R.id.mainView);

    Cursor c = dbase.query("SELECT letter, number from database");

    while (c.moveToNext()){
        TextView t = new TextView(this);
        t.setText(c.getString(c.getColumnIndex("letter"))+","+c.getLong(c.getColumnIndex("number")));
        my_layout.addView(t);
    }
    c.close();

现在我第一次按下我的应用程序上的按钮时可以正常显示我的数据,但问题是在后续按下时,已经显示的数据仍保留在屏幕上,最终屏幕用完 space.

例如,按一次:

A,45
B,57

再按一下:

A,45
B,57
A,45
B,57

等等。

如何修改我的循环,以便在每次新按下时擦除屏幕的当前内容?任何帮助表示赞赏。

您可以在重新填充之前从布局中删除所有视图:

LinearLayout my_layout = (LinearLayout)findViewById(R.id.mainView);
my_layout.removeAllViews();

Cursor c = dbase.query("SELECT letter, number from database");
while (c.moveToNext()){
    TextView t = new TextView(this);
    t.setText(c.getString(c.getColumnIndex("letter"))+","+c.getLong(c.getColumnIndex("number")));
    my_layout.addView(t);
}
c.close();

或者如果 Layout 中有其他视图使用列表来存储生成的 TextView,只要您单击按钮,这些 TextView 就会被清除并重新填充。
所以在 activity class 级别定义列表:

List<TextView> list;

并在 onCreate() 中初始化它:

list = new ArrayList<>();

然后像这样修改你的监听器:

LinearLayout my_layout = (LinearLayout) findViewById(R.id.mainView);
for (TextView t : list) {
    my_layout.removeView(t);
}
list.clear();

Cursor c = dbase.query("SELECT letter, number from database");
while (c.moveToNext()){
    TextView t = new TextView(this);
    t.setText(c.getString(c.getColumnIndex("letter"))+","+c.getLong(c.getColumnIndex("number")));
    my_layout.addView(t);
    list.add(t);
}
c.close();