看代碼,定義一個容器名字為 ll_root,在裡面建立 5 個子 View;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"/>
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:gravity="center"/>
</LinearLayout>
将容器内的5個子 View 周遊出來,并設定内容:
ll_root = findViewById(R.id.ll_root);
for (int i = 0; i < ll_root.getChildCount(); i++) {
TextView textView = (TextView) ll_root.getChildAt(i);
textView.setText("容器總長度為" + ll_root.getChildCount() + "目前是第" + i + "個");
}
這樣就成功為每一個 TextView 設定上了顯示的内容,如下圖:
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHL9UkaixmTzoVdsd1YxQ2MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL2kzNyAjN1UTM1AjMxgTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)