androidviewandroid-edittextrootview

Get specific type of view from parent view


Do you guys know if there's a proper manner to get all specific view types from the parent view as the title says?

I would like to get all the EditText views from my activity, so I wonder if there's a better way than using this solution get all views from an activity and then testing every view to check if it's an EditText or not?

Thank you for the help,

Florian


Solution

  • Approach 1 :

    Let's say you named your edittext edittext_0, edittext_1, .. edittext_n. You can do:

    ViewGroup vg = (ViewGroup) view;
    for (int i = 0; i < n; i++) {
        int id = vg.getResources().getIdentifier("edittext_"+i, "id", getPackageName());
         edittext[i] = (EditText) vg.findViewById(id);
    }
    

    Actually the answers specified in the link given, are feasible if you have a large number of views, but if you want a specific type of view from a view/viewgroup, simply use findViewById method. Example :

    (in Kotlin) //Similar syntax in java
    val view : View = findViewById(your_layout_or_any_other_view)
    val childView : EditText = view.findViewById(edittext_id)
    

    OPTIONAL READING

    Optimised Answer for the answers given in link :

    It is easier with Kotlin using for-in loop:

    for (childView in ll.children) {
         if(childView.id == your_edittext_id) //If required
         //childView is a child of ll         
    }
    //Here ll is id of LinearLayout defined in layout XML.