Null Validation on EditText box in Alert Dialog - Android

后端 未结 6 1355
有刺的猬
有刺的猬 2021-01-02 23:15

I am trying to add some text validation to an edit text field located within an alert dialog box. It prompts a user to enter in a name.

I want to add some validatio

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-03 00:07

    Even though it's an old post, the code below will help somebody. I used a customized layout and extended DialogFragment class.

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    
        // Get the layout inflater
        LayoutInflater inflater = requireActivity().getLayoutInflater();
    
        final View view = inflater.inflate(R.layout.Name_of_the_customized_layout, null);
    
        final EditText etxtChamp = view.findViewById(R.id.editText);
    
    
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage("Enter a Name")
                .setTitle("Mandatory field ex.");
    
        builder.setView(view);
    
        final Button btnOk = view.findViewById(R.id.ok);
        final Button btnCancel = view.findViewById(R.id.cancel);
    
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(etxtChamp.getText().toString().isEmpty()){
                    etxtChamp.setError("Oups! ce champ est obligatoire!");
                }else{
                    //Get the editText content and do whatever you want
                    String messageEditText = etxtChamp.getText().toString();
    
                    dismiss();
                }
            }
        });
    
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
    
        return builder.create();
    }
    

提交回复
热议问题