ViewGroup直下の全ての子にアクセスする
AndroidでViewGroup直下にある子Viewを全て取得したくなりました。
(正確にはViewGroupを継承しているFrameLayoutやLinearLayoutでの話)
以下のコードは、
LinearLayout(@id="ll_parent")直下のTextViewを全て取得し、
テキストをセットしています。
LinearLayout parent = (LinearLayout)findViewById(R.id.ll_parent); TextView textView; for (int i = 0; i < parent.getChildCount(); i++) { textView = (TextView)parent.getChildAt(i); textView.setText((i + 1) + "番目のView"); }
<LinearLayout android:id="@+id/ll_parent" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="10"> <TextView android:id="@+id/v_child_1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> <TextView android:id="@+id/v_child_2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> <TextView android:id="@+id/v_child_3" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> <TextView android:id="@+id/v_child_4" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> <TextView android:id="@+id/v_child_5" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /> </LinearLayout>
ViewGroup直下にある全ての子Viewにアクセスするには | GE Android Blog
うどん職人 | カガワウェブ