J'ai un LinearLayout
qui contient plusieurs enfants TextViews
. Comment puis-je obtenir des vues enfant de ce LinerLayout en utilisant une boucle ?
Réponses
Trop de publicités?
Favas Kv
Points
46
((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.
Ici, je n'itère que les EdiTexts, si vous voulez toutes les vues, vous pouvez remplacer EditText par View.
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);
}
}
}
Malwinder Singh
Points
2280
Роман Зыков
Points
153
utiliser ce
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()));
}
}
NJY404
Points
123
Obtenez toutes les vues de n'importe quel type de mise en page
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;
}
Récupérer tous les TextView de n'importe quel type de mise en page
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;
}