簡體   English   中英

警報對話框中的EditText框上的空驗證 - Android

[英]Null Validation on EditText box in Alert Dialog - Android

我正在嘗試向位於警告對話框中的編輯文本字段添加一些文本驗證。 它會提示用戶輸入名稱。

我想添加一些驗證,以便如果他們輸入的內容為空或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。 我希望警報對話框仍然在屏幕上。

謝謝

我認為你應該重新創建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返回一個AlertDialog.Builder對象,你可以直接調用一個方法。

Toast的情況也是如此:

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

我在我的類中創建了一個新方法,它顯示了警報,並在該方法中放置了用於創建警報的所有代碼。 然后在調用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);

        }
}

你應該做的是創建一個自定義的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;
}

//如果未實例化視圖,則始終為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); 

即使它是一個舊帖子,下面的代碼將幫助某人。 我使用了自定義布局和擴展的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();
}

使用此代碼顯示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();            
            }

這將為您創建一個Dialog, editText為空或您想要的條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM