editText field is required before moving on to another Activity

后端 未结 7 1309
情深已故
情深已故 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 17:57

    I know this is an old post, but I needed similar functionality in my application, so I deciced to develop a simple but powerful validator for ease of re-use.

    link for github repo It's super easy to use.

    1. Create a list of the fields you want to be mandatory
    2. Call validateViewFields method and pass the list of views

    code example for Activity:

        public class AddContractActivity extends AppCompatActivity {
    
        TextView contractDescriptionTextView;
        TextView totalAmountTextView;
    
        List fieldsToBeValidated;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_add_contract);
    
            contractDescriptionTextView = findViewById(R.id.contractDescriptionEditText);
            totalAmountTextView = findViewById(R.id.totalAmountText);
    
            fieldsToBeValidated = new ArrayList<>(Arrays.asList(
                    contractDescriptionTextView,
                    totalAmountTextView));
    
            saveButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!UIValidator.validateViewFields(fieldsToBeValidated, true)) {
                        Toast.makeText(AddContractActivity.this, "Missing Fields", Toast.LENGTH_SHORT).show();
                        mainScrollView.post(new Runnable() {
                            @Override
                            public void run() {
                                mainScrollView.smoothScrollTo(0, 0);
                            }
                        });
                        return;
                    }
                }
            });
        }
    }
    

提交回复
热议问题