我有LinearLayout
,其中包含多个子TextViews
。如何使用循环获取该LinerLayout的子视图?
答案 0 :(得分:255)
使用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.
// …
}
答案 1 :(得分:37)
( (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替换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);
}
}
}
答案 2 :(得分:3)
使用此
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()));
}
}
答案 3 :(得分:1)
从任何类型的布局获取所有视图
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;
}
答案 4 :(得分:0)
使用Kotlin更容易:
for (child in ll.children) {
//child is a View
}
此处ll
是用XML定义的LinearLayout
。
答案 5 :(得分:0)
在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)
}