一次获取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())); } }
- 如何改变CheckBox的颜色?
- 如何处理:java.util.concurrent.TimeoutException:android.os.BinderProxy.finalize()10秒后超时错误?
- 如何从android的webview的JavaScript中获得返回值?
- 使用Fragments在Android中为每个选项卡单独备份堆栈
- 为我的android应用程序select正确的API级别
- 无尽的RecyclerView与ProgressBar分页
- 以共享首选项存储和检索类对象
- Nexus 7(2013)和Win 7 64 – 无法安装USB驱动程序,尽pipe检查了许多论坛和在线资源
- 如何将图像转换为Base64字符串?