TextViews 文本在 for 循环中更改

2022-01-09 00:00:00 for-loop android java textview

我想在 Android Studio 的 for 循环中更改 textViews 的文本,如下所示:

I want to change textViews' texts inside for loop in Android Studio, something like that:

for i=0 ------------> textView0 设置文本默认"

for i=0 ------------> textView0 set text "Default"

for i=1 ------------> textView1 设置文本默认"

for i=1 ------------> textView1 set text "Default"

for i=2 ------------> textView2 设置文本默认"

for i=2 ------------> textView2 set text "Default"

有可能做到吗?我不知道如何根据i"值更改循环内的textView id,有人可以帮助我吗?

Is it possible to do that? I don't know how to change the textView id inside the loop according to "i" value, can someone help me?

这是我的 XML:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="--------------"
    android:id="@+id/textView0"
    android:layout_marginLeft="16dp"
    android:layout_gravity="center_horizontal"
    android:textSize="13dp" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="--------------"
    android:id="@+id/textView1"
    android:layout_gravity="center_horizontal"
    android:layout_marginLeft="16dp"
    android:textSize="13dp" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceSmall"
    android:text="--------------"
    android:id="@+id/textView2"
    android:layout_gravity="center_horizontal"
    android:layout_marginLeft="16dp"
    android:textSize="13dp" />

推荐答案

性能明智的好方法.

    int[] textViews = {R.id.textView1, R.id.textView2, R.id.textView3};
    String[] messages = {"one", "two", "three"};

     for (int i = 0; i < 3; i++) {
            TextView tv = (TextView) findViewById(textViews[i]);
            tv.setText(messages[i]);
        }

相关文章