天天看點

Android周遊出容器中的子view

看代碼,定義一個容器名字為 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 設定上了顯示的内容,如下圖:

Android周遊出容器中的子view