Method to get all EditTexts in a View

后端 未结 5 685
无人共我
无人共我 2020-11-30 07:58

can anyone help me with coding a method to get all EditTexts in a view? I would like to implement the solution htafoya posted here: How to hide soft keyboard on android afte

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 08:11

    Here's a method I wrote to recursively check all EditText children of a ViewGroup, handy for a long sign-up form I had to do and probably more maintainable.

    private EditText traverseEditTexts(ViewGroup v)
    {
        EditText invalid = null;
        for (int i = 0; i < v.getChildCount(); i++)
        {
            Object child = v.getChildAt(i); 
            if (child instanceof EditText)
            {
                EditText e = (EditText)child;
                if(e.getText().length() == 0)    // Whatever logic here to determine if valid.
                {
                    return e;   // Stops at first invalid one. But you could add this to a list.
                }
            }
            else if(child instanceof ViewGroup)
            {
                invalid = traverseEditTexts((ViewGroup)child);  // Recursive call.
                if(invalid != null)
                {
                    break;
                }
            }
        }
        return invalid;
    }
    
    private boolean validateFields()
    {   
        EditText emptyText = traverseEditTexts(mainLayout);
        if(emptyText != null)
        {
            Toast.makeText(this, "This field cannot be empty.", Toast.LENGTH_SHORT).show();
            emptyText.requestFocus();      // Scrolls view to this field.
        }
        return emptyText == null;
    }
    

提交回复
热议问题