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

发布于 2024-08-27 13:36:03 字数 1547 浏览 6 评论 0原文

我正在尝试向位于警报对话框内的编辑文本字段添加一些文本验证。它提示用户输入名称。

我想添加一些验证,这样如果他们输入的内容为空或为空,除了创建一个显示错误的 Toast 之外,它不会执行任何操作。

到目前为止,我已经:

    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);

            }

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

谢谢

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.

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.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

ゃ人海孤独症 2024-09-03 13:36:03

我认为你应该重新创建 Dialog,因为在 onClick() 中作为参数给出的 DialogInterface 似乎没有给你一个选项停止Dialog的关闭。

我还为您提供了一些提示:

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

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

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

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

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

对于 Toast 也是如此:

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

I think you should recreate the Dialog, as it seems the DialogInterface given as a parameter in onClick() doesn't give you an option to stop the closure of the 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.

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:

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.Builder return an AlertDialog.Builder object, which you can directly call a method on.

The same goes for Toasts:

Toast.makeText(this, "Please enter...", Toast.LENGTH_LONG).show();
征﹌骨岁月お 2024-09-03 13:36:03

我在类中创建了一个新方法来显示警报,并将用于创建警报的所有代码放入该方法中。然后在调用 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);

        }
}

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,

  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);

        }
}
陌路终见情 2024-09-03 13:36:03

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

它应该在 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;
}

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.

It should be used in 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;
}
风筝有风,海豚有海 2024-09-03 13:36:03

尽管这是一篇旧文章,但下面的代码会对某人有所帮助。我使用了自定义布局和扩展的 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 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();
}

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();
}
倾城泪 2024-09-03 13:36:03

使用此代码显示对话框。

 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();            
            }

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

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, editText is empty or what are conditions you wants.

深空失忆 2024-09-03 13:36:03

//如果视图没有实例化,它总是为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); 

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

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); 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文