Java 警报对话框中 EditText 框的空验证 - Android

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2580606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:28:13  来源:igfitidea点击:

Null Validation on EditText box in Alert Dialog - Android

javaandroidvalidationalert

提问by jcrowson

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 validation so that if what they have entered is blank or null, it does not do anything apart from creating a Toast saying error.

我想添加一些验证,以便如果他们输入的是空白或空值,除了创建 Toast 说错误之外,它不会做任何事情。

So far I have:

到目前为止,我有:

    AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Record New Track");
    alert.setMessage("Please Name Your Track:");
    // Set an EditText view to get user input
    final EditText trackName = new EditText(this);
    alert.setView(trackName);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {

            String textString = trackName.getText().toString(); // Converts the value of getText to a string.
            if (textString != null && textString.trim().length() ==0)
            {   

                Context context = getApplicationContext();
                CharSequence error = "Please enter a track name" + textString;
                int duration = Toast.LENGTH_LONG;

                Toast toast = Toast.makeText(context, error, duration);
                toast.show();


            }
            else 
            {

                SQLiteDatabase db = waypoints.getWritableDatabase();
                ContentValues trackvalues = new ContentValues();
                trackvalues.put(TRACK_NAME, textString);
                trackvalues.put(TRACK_START_TIME,tracktimeidentifier );
                insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues);

            }

But this just closes the Alert Dialog and then displays the Toast. I want the Alert Dialog to still be on the screen.

但这只是关闭警报对话框,然后显示 Toast。我希望警报对话框仍然在屏幕上。

Thanks

谢谢

采纳答案by MrSnowflake

I think you should recreate the Dialog, as it seems the DialogInterfacegiven as a parameter in onClick()doesn't give you an option to stop the closure of the Dialog.

我想你应该重新创建Dialog,因为它似乎在DialogInterface给定的参数onClick()不给你一个选择停止的关闭Dialog

I also have a couple of tips for you:

我也有一些提示给你:

Try using Activity.onCreateDialog(), Activity.onPrepareDialog()and of course Activity.showDialog(). They make dialog usage much easier (atleast for me), also dialog usage looks more like menu usage. Using these methods, you will also be able to more easilty show the dialog again.

尝试使用Activity.onCreateDialog()Activity.onPrepareDialog()当然Activity.showDialog()。它们使对话框使用更容易(至少对我而言),而且对话框使用看起来更像是菜单使用。使用这些方法,您还可以更轻松地再次显示对话框。

I want to give you a tip. It's not an answer to your question, but doing this in an answer is much more readable.

我想给你一个提示。这不是您问题的答案,但在答案中这样做更具可读性。

Instead of holding a reference to an AlertDialog.Builder()object, you can simply do:

AlertDialog.Builder()您可以简单地执行以下操作,而不是持有对对象的引用:

new AlertDialog.Builder(this)
.setTitle("Record New Track")
.setMessage("Please Name Your Track:")
//and some more method calls
.create();
//or .show();

Saves you a reference and a lot of typing ;). (almost?) All methods of AlertDialog.Builderreturn an AlertDialog.Builderobject, which you can directly call a method on.

为您节省参考和大量输入;)。(几乎?)AlertDialog.Builder返回一个AlertDialog.Builder对象的所有方法,您可以直接调用一个方法。

The same goes for Toasts:

这同样适用于ToastS:

Toast.makeText(this, "Please enter...", Toast.LENGTH_LONG).show();

回答by fernandojsg

What you should do is to create a custom xml layout including a textbox and an Ok button instead of using .setPositiveButton. Then you can add a click listener to your button in order to validate the data and dismiss the dialog.

您应该做的是创建一个自定义 xml 布局,包括一个文本框和一个 Ok 按钮,而不是使用 .setPositiveButton。然后,您可以向按钮添加一个单击侦听器,以验证数据并关闭对话框。

It should be used in CreateDialog:

它应该在 CreateDialog 中使用:

protected Dialog onCreateDialog(int id) 
{
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

if (id==EDIT_DIALOG)
{
            final View layout = inflater.inflate(R.layout.edit_dialog, (ViewGroup) findViewById(R.id.Layout_Edit));

            final Button okButton=(Button) layout.findViewById(R.id.Button_OkTrack);
            final EditText name=(EditText) layout.findViewById(R.id.EditText_Name);
            okButton.setOnClickListener(new View.OnClickListener() 
            {
                public void onClick(View v) {
                    String textString = trackName.getText().toString(); 
                    if (textString != null && textString.trim().length() ==0)
                    {
                        Toast.makeText(getApplicationContext(), "Please enter...", Toast.LENGTH_LONG).show();
                    } else
                        removeDialog(DIALOG_EDITTRACK);
                }
            });            
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setView(layout);
            builder.setTitle("Edit text");

            AlertDialog submitDialog = builder.create();            
            return submitDialog;
}

回答by Mona

I make a new method inside my class that shows the alert and put all the code for creating the alert in that one method. then after calling the Toast I call that method. Say I named that method createAlert(), then I have,

我在我的类中创建了一个显示警报的新方法,并将用于创建警报的所有代码放在该方法中。然后在调用 Toast 之后我调用该方法。假设我将该方法命名为 createAlert(),然后我有,

  createAlert(){

 AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Record New Track");
alert.setMessage("Please Name Your Track:");
// Set an EditText view to get user input
final EditText trackName = new EditText(this);
alert.setView(trackName);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {

        String textString = trackName.getText().toString(); // Converts the value of getText to a string.
        if (textString != null && textString.trim().length() ==0)
        {   

            Context context = getApplicationContext();
            CharSequence error = "Please enter a track name" + textString;
            int duration = Toast.LENGTH_LONG;

            Toast toast = Toast.makeText(context, error, duration);
            toast.show();
            createAlert();



        }
        else 
        {

            SQLiteDatabase db = waypoints.getWritableDatabase();
            ContentValues trackvalues = new ContentValues();
            trackvalues.put(TRACK_NAME, textString);
            trackvalues.put(TRACK_START_TIME,tracktimeidentifier );
            insertid=db.insertOrThrow(TRACK_TABLE_NAME, null, trackvalues);

        }
}

回答by Avinash

Use This code for displaying Dialog.

使用此代码显示对话框。

 public void onClick(DialogInterface dialog, int whichButton) {

            String textSt`enter code here`ring = trackName.getText().toString(); // Converts the value of getText to a string.
            if (textString != null && textString.trim().length() ==0)
            {       
                Context context = getApplicationContext();
                CharSequence error = "Please enter a track name" + textString;
                int duration = Toast.LENGTH_LONG;

                Toast toast = Toast.makeText(context, error, duration);
                toast.show();

                new AlertDialog.Builder(this)
                .setTitle("Message")
                .setMessage("please enter valid field")
                .setPositiveButton("OK", null).show();            
            }

This will create a Dialog for you, editTextis empty or what are conditions you wants.

这将为您创建一个对话框,editText是空的还是您想要的条件。

回答by Swapnil Kotwal

//if view is not instantiated,it always returns null for edittext values.

//如果视图没有被实例化,它总是为edittext值返回null。

View v = inflater.inflate(R.layout.new_location_dialog, null);
builder.setView(v); 



final EditText titleBox = (EditText)v.findViewById(R.id.title);
final EditText descriptionBox = (EditText)v.findViewById(R.id.description); 

回答by ASM

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

即使这是一个旧帖子,下面的代码也会对某人有所帮助。我使用了自定义布局和扩展的 DialogFragment 类。

@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 obligattheitroade!");
            }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();
}