Answers:
使用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.
// …
}
buttons
线性布局中未添加的总数,并将其除以2?我的目的是使用线性布局显示2行按钮。
((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,如果您想要所有View,可以将View替换为EditText。
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);
}
}
}
getChildAt
仅返回直接子对象
用这个
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()));
}
}
从任何类型的布局获取所有视图
public List<View> getAllViews(ViewGroup layout){
List<View> views = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
views.add(layout.getChildAt(i));
}
return views;
}
从任何类型的布局获取所有TextView
public List<TextView> getAllTextViews(ViewGroup layout){
List<TextView> views = new ArrayList<>();
for(int i =0; i< layout.getChildCount(); i++){
View v =layout.getChildAt(i);
if(v instanceof TextView){
views.add((TextView)v);
}
}
return views;
}
在Kotlin中递归获取视图及其子视图的所有视图:
private fun View.getAllViews(): List<View> {
if (this !is ViewGroup || childCount == 0) return listOf(this)
return children
.toList()
.flatMap { it.getAllViews() }
.plus(this as View)
}