一次获取LinearLayout中的所有子视图

我有一个LinearLayout ,它包含几个子TextViews 。 如何使用循环获取LinerLayout的子视图?

使用getChildCount()getChildAt(int index)

例:

 LinearLayout ll = … final int childCount = ll.getChildCount(); for (int i = 0; i < childCount; i++) { View v = ll.getChildAt(i); // Do something with v. // … } 
  ( (ViewGroup) findViewById(android.R.id.content));// you can use this in an Activity to get your layout root view, then pass it to findAllEdittexts() method below. 

在这里我迭代只有EdiTexts,如果你想要所有的视图,你可以用ViewreplaceEditText。

 SparseArray<Edittext> array = new SparseArray<Edittext>(); private void findAllEdittexts(ViewGroup viewGroup) { int count = viewGroup.getChildCount(); for (int i = 0; i < count; i++) { View view = viewGroup.getChildAt(i); if (view instanceof ViewGroup) findAllEdittexts((ViewGroup) view); else if (view instanceof Edittext) { Edittext edittext = (Edittext) view; array.put(edittext.getId(), edittext); } } } 

用这个

  final int childCount = mainL.getChildCount(); for (int i = 0; i < childCount; i++) { View element = mainL.getChildAt(i); // EditText if (element instanceof EditText) { EditText editText = (EditText)element; System.out.println("ELEMENTS EditText getId=>"+editText.getId()+ " getTag=>"+element.getTag()+ " getText=>"+editText.getText()); } // CheckBox if (element instanceof CheckBox) { CheckBox checkBox = (CheckBox)element; System.out.println("ELEMENTS CheckBox getId=>"+checkBox.getId()+ " getTag=>"+checkBox.getTag()+ " getText=>"+checkBox.getText()+" isChecked=>"+checkBox.isChecked()); } // DatePicker if (element instanceof DatePicker) { DatePicker datePicker = (DatePicker)element; System.out.println("ELEMENTS DatePicker getId=>"+datePicker.getId()+ " getTag=>"+datePicker.getTag()+ " getDayOfMonth=>"+datePicker.getDayOfMonth()); } // Spinner if (element instanceof Spinner) { Spinner spinner = (Spinner)element; System.out.println("ELEMENTS Spinner getId=>"+spinner.getId()+ " getTag=>"+spinner.getTag()+ " getSelectedItemId=>"+spinner.getSelectedItemId()+ " getSelectedItemPosition=>"+spinner.getSelectedItemPosition()+ " getTag(key)=>"+spinner.getTag(spinner.getSelectedItemPosition())); } }