Get all child views inside LinearLayout at once

前端 未结 6 2184
野性不改
野性不改 2020-11-28 04:39

I have a LinearLayout, which contains several child TextViews. How can I get child views of that LinerLayout using a loop?

6条回答
  •  青春惊慌失措
    2020-11-28 05: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.
    

    Here I am iterating only EdiTexts, if you want all Views you can replace EditText with View.

    SparseArray array = new SparseArray();
    
    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);
            }
        }
    }
    

提交回复
热议问题