Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

java - TextViews text change in a for loop

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

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

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

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

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?

Here's my 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" />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Performance wise good approach.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...