Validate Edittext within Alertdialog

Asked

Viewed 355 times

1

I have a AlertDialog and inside of it I have a EditText and need to validate and after validate run the method enviarEmail(), how do I do?

Man AlertDialog :

AlertDialog.Builder caixaDialog = new AlertDialog.Builder(getContext());
            caixaDialog.setView(vView)
                    .setCancelable(false)
                    .setPositiveButton("Enviar", null)
                    .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                            // Habilitar todos os botões
                            btnSatisfacaoRuim.setBackgroundResource(R.drawable.img_satisfacao_ruim);
                            btnSatisfacaoBom.setBackgroundResource(R.drawable.img_satisfacao_bom);
                            btnSatisfacaoNormal.setBackgroundResource(R.drawable.img_satisfacao_normal);
                            llSatisfacao.setVisibility(View.INVISIBLE);

                        }
                    });

            final AlertDialog mDialog = caixaDialog.create();
            mDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    Button positive = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
                    positive.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (edtMensagemSatEmail.getText().length() == 0) {
                                edtMensagemSatEmail.setError("Campo obrigatório");
                                edtMensagemSatEmail.setFocusable(true);
                                edtMensagemSatEmail.requestFocus();
                            } else {
                                // Barra de progresso
                                progresso = new ProgressDialog(getContext());
                                progresso.setCancelable(false);
                                progresso.setMessage("Processando...");
                                progresso.show();

                                // Metodo de envio
                                inserirWEBService();
                                enviarEmail();
                                mDialog.dismiss();
                            }
                            getFragmentManager().beginTransaction().replace(R.id.content_principal, new avalieViagem()).addToBackStack(null).commit();
                        }
                    });
                }
            });

            mDialog.show();

My XML from Dialog:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:background="#ffffff"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Linha: "
            android:textColor="#548ddf"
            android:textSize="18dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/txt_linha_sat_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="linha"
            android:textColor="#548ddf"
            android:textSize="18dp"
            android:textStyle="bold"
            app:layout_constraintStart_toEndOf="@+id/textView"
            app:layout_constraintTop_toTopOf="parent" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Horário: "
            android:textColor="#548ddf"
            android:textSize="18dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView" />

        <TextView
            android:id="@+id/txt_horario_sat_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="horario"
            android:textColor="#548ddf"
            android:textSize="18dp"
            android:textStyle="bold"
            app:layout_constraintStart_toEndOf="@+id/textView1"
            app:layout_constraintTop_toBottomOf="@+id/txt_linha_sat_email" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/img_sat_email"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_marginTop="5dp"
            app:srcCompat="@drawable/img_satisfacao_bom_off"
            tools:layout_editor_absoluteX="10dp"
            tools:layout_editor_absoluteY="69dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <TextView
            android:id="@+id/txt_satisfacao_sat_email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="satisfacao"
            android:textColor="#548ddf"
            android:textSize="18dp"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/img_sat_email" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:text="Deixe seu Comentário:"
            android:textColor="#548ddf"
            android:textSize="18dp" />

        <EditText
            android:id="@+id/txt_Mensagem_sat_email"
            android:layout_width="250dp"
            android:layout_height="100dp"
            android:layout_marginTop="0dp"
            android:background="#d8d6d3"
            android:gravity="top|left"
            android:hint="Comente aqui"
            android:inputType="textMultiLine"
            android:lines="6"
            android:overScrollMode="always"
            android:scrollbarStyle="insideInset"
            android:scrollbars="vertical"
            android:scrollHorizontally="false"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#000000" />

    </LinearLayout>

</LinearLayout>
  • What’s wrong with your code?

  • He’s not validating the EditText when I click Send AlertDialog.

  • txtMensagemSatEmail is a Textview ta wanting to validate a Textview? Ta validating something based on a Textview ?

  • He is a EditText, was only the variable name.

  • It wouldn’t be enough for one return at the end of the code within the if?

  • Put, just closed the AlertDialog.

  • If you want to keep the dialog open in case the entered data is not valid see this reply.

  • I couldn’t, in the second step, I freeze, in the part of declaring the button, there is no setButton.

Show 3 more comments

2 answers

0

In the creation of the event Voce is placing edtMensagemSatEmail = (Textview) and not edtMensagemSatEmail = (Edittext )

and put on Isis

if (edtMensagemSatEmail.getText().length() == 0) {
                        edtMensagemSatEmail.setError("Campo obrigatório");
                        edtMensagemSatEmail.setFocusable(true);
                        edtMensagemSatEmail.requestFocus();
                    }
else
    enviarEmail();

probably validates yes, but soon after goes to the method send Mail(); and there you must have put some routine to close, if put in Lse it only goes to send Mail() if you pass the validation.

  • even with EditText is not validating, when I click send pass through.

  • edited the answer

  • I think I was missing This test again

  • Right, it doesn’t send. Only it closes the AlertDialog, wanted him to have the Dialog open and set in the field edtMensagemSatEmail.setError("Campo obrigatório");

0


Hello, to treat a button click event in alertdialog, without it close, call the método setOnShowListener (new DialogInterface.OnShowLister); In this method you retrieve the Positive button to handle the event in the click inside the onShow() method, follow the example for your code:

View vView = getLayoutInflater().inflate(R.layout.envio_satisfacao_ruim, null);
        edtMensagemSatEmail = (EditText) vView.findViewById(R.id.edt_Mensagem_sat_email);
        edtMensagemSatEmail.setFocusable(true);



AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Seu Titulo")
            .setView( vView)
            .setCancelable(false)
            .setPositiveButton("Enviar", null)
            .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    final AlertDialog mDialog = builder.create();
    //Aqui você trata o click do button positive sem que o alertdialog feche em caso de convergência
    mDialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(final DialogInterface dialog) {
            Button postive = mDialog.getButton(AlertDialog.BUTTON_POSITIVE);
            postive.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //aqui você trata o evento
                    if (edtMensagemSatEmail.getText().length() == 0) {
                        edtMensagemSatEmail.setError("Campo obrigatório");
                        edtMensagemSatEmail.setFocusable(true);
                        edtMensagemSatEmail.requestFocus();
                    } else {
                        //Como ao clicar no botão positivo a condição é verificada
                        //caso esteja tudo certo com o edittext, então chama o seu método
                        //enviar email
                        enviarEmail();
                        //No final como já completou a condição pode dar dismiss
                        //no alertdialog, pois está tudo ok
                        dialog.dismiss();

                    }

                }
            });
        }
    });
    mDialog.show();

Note: I did not test, but I’m sure it’s working for your need. Working or not, give a feedback. Hug

  • hello, it spun, but still continues to close the alert if you do not report anything on EditText, edited and posted my updated by your.

  • Even though we EditText Is closing the Dialog without doing the deed

  • @Arimelo tested and is working yes, follow faithfully my answer that will work. By the code you edited at the end of the alertdialog you are calling: caixaDialog.setView(vView);&#xA; AlertDialog dialog = caixaDialog.create();&#xA; dialog.show(); Ie, is recreating the alert without onShow methods. So remove that part and put only: mDialog.show();

  • Just correcting me, there at the end of alertdialog by your code, you are creating another view pro dialog, and not creating a new alert. This overrides the methods that are handling the click event.

  • It didn’t work when you open the Dialog, shows only the cancel and send buttons nothing else, as if the body disappeared, I edited again the way the project is.

  • Is there any way to put the xml on your alert? The code should be working. I tested this one on an api 28 and it’s OK. The only difference in your code is in the method of the Cancel button, put the dialog.Cell at the end of the method, because the methods below are not executed. And in positive button click filling instead of mDialog.Ismiss(); it’s dialog.Ismiss()

  • Posted in Home.

  • 1

    Instead of using his own buttons AlertDialog, I created 2 buttons in the layout, and it worked validation, vlw.

  • Nice brother, but weird this way with the alertdialog buttons not go.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.