editText field is required before moving on to another Activity

后端 未结 7 1300
情深已故
情深已故 2021-01-30 17:14

I have validation for editText. If the editText field is empty it should fail validation and stop the user moving on to another Activity,

相关标签:
7条回答
  • 2021-01-30 18:06

    I faced a similiar problem. In my case, I had a lot of Edittexts to verify, some them was child of another layouts. Tip: all views must be in same root view. So, to be simple:

    ...
    LinearLayout viewGroup = (LinearLayout) findViewById(R.id.viewGroup);
    checkFieldsRequired(viewGroup);
    ...
    
    public boolean checkFieldsRequired(ViewGroup viewGroup){
    
        int count = viewGroup.getChildCount();
        for (int i = 0; i < count; i++) {
            View view = viewGroup.getChildAt(i);
            if (view instanceof ViewGroup)
                checkFieldsRequired((ViewGroup) view);
            else if (view instanceof EditText) {
                EditText edittext = (EditText) view;
                if (edittext.getText().toString().trim().equals("")) {                  
                    edittext.setError("Required!");                 
                }
            }
        }
    
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题