立即获取 LinearLayout 中的所有子视图

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

117679 次浏览

使用 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.

这里我只迭代 EditText,如果你想要所有的视图,你可以用 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);
}
}
}

用这个

    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()));
}


}

Kotlin 使用 for-in 循环更容易:

for (childView in ll.children) {
//childView is a child of ll
}

这里的 ll是在布局 XML 中定义的 LinearLayoutid

返回文章页面 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)
}

从任何类型的布局获取所有视图

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;
}