7

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

我想添加一些验证,以便如果他们输入的内容是空白或 null,除了创建 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。我希望警报对话框仍然在屏幕上。

谢谢

4

6 回答 6

4

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

        }
}
于 2011-11-22T04:18:13.967 回答
4

DialogDialogInterface认为您应该重新onClick()创建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对象,您可以直接在该对象上调用一个方法。

s也是如此Toast

Toast.makeText(this, "Please enter...", Toast.LENGTH_LONG).show();
于 2010-04-05T20:36:18.317 回答
3

您应该做的是创建一个自定义 xml 布局,包括一个文本框和一个 Ok 按钮,而不是使用 .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;
}
于 2010-10-24T21:53:56.720 回答
2

即使这是一篇旧文章,下面的代码也会对某人有所帮助。我使用了自定义布局和扩展的 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();
}
于 2019-08-06T20:11:47.613 回答
0

//如果视图没有实例化,它总是为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); 
于 2013-03-05T12:02:55.197 回答
0

使用此代码显示对话框。

 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为空或您想要什么条件。

于 2012-01-24T04:06:45.387 回答