2015-01-07 6 views
0

Я проверяю наличие недопустимого ввода в группу редактируемых текстов в диалоговом окне предупреждения, проверяя нулевой ввод и вызывая setError. Но в моей текущей реализации диалог все еще закрывается, несмотря на то, что был введен неверный ввод.Использование setError для проверки правильности ввода текста Android

Логическое проверка была добавлена ​​к каждому тексту редактирования, чтобы предотвратить диалог от увольнения, если какой-либо из редактирования текстов установить логическое значение ЛОЖЬ, как это:

 else if(TextUtils.isEmpty(strColour)) { 
     colourText.setError("Please enter a value"); 
     entriesValid = false; 

` Но диалог все-таки уволили несмотря на недопустимый ввод.

Мой вопрос, что здесь ошибка, позволяющая закрыть диалоговое окно с недопустимым вводом?

Я установил точку останова в этой строке, if(entriesValid), чтобы проверить, не вызвано ли условие, но это не означает, что проверка будет пропущена.

Это полный диалог пользовательский класс:

public class MyMessageDialog { 

    public interface MyMessageDialogListener { 
     public void onClosed(String ship, String scientist, String email, String volume, String color); 
    } 

@SuppressLint("NewApi") 
public static AlertDialog displayMessage(Context context, String title, String message, final MyMessageDialogListener listener){ 
    AlertDialog.Builder builder = new AlertDialog.Builder(context); 
    LayoutInflater inflater = LayoutInflater.from(context); 
    builder.setTitle(title); 
    builder.setMessage(message); 
    final View layoutView = inflater.inflate(R.layout.custom_view, null); 
    builder.setView(layoutView); 
    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
    @Override 
    public void onClick(DialogInterface dialog, int which) { 
     boolean entriesValid = true; 
     // get the edit text values here and pass them back via the listener 
     if(listener != null) 
     { 
     EditText shipText = (EditText)layoutView.findViewById(R.id.shipNameEditText); 
     EditText scientistNameText = (EditText)layoutView.findViewById(R.id.scientistEditText); 
     EditText scientistEmailText = (EditText)layoutView.findViewById(R.id.emailEditText); 
     EditText volumeText = (EditText)layoutView.findViewById(R.id.volumeEditText); 
     EditText colourText = (EditText)layoutView.findViewById(R.id.colourEditText); 



     listener.onClosed(shipText.getText().toString(), 
       scientistNameText.getText().toString(), 
       scientistEmailText.getText().toString(), 
       volumeText.getText().toString(), 
       colourText.getText().toString()); 

     String strShipName = shipText.getText().toString(); 
     String strScientistName = scientistNameText.getText().toString(); 
     String strScientistEmail = scientistEmailText.getText().toString(); 
     String strVolume = volumeText.getText().toString(); 
     String strColour = colourText.getText().toString(); 
     if(TextUtils.isEmpty(strShipName)) { 
      shipText.setError("Please enter a value"); 
      entriesValid = false; 
     } 
     else if(TextUtils.isEmpty(strShipName)) { 
      shipText.setError("Please enter a value"); 
      entriesValid = false; 
     } 
     else if(TextUtils.isEmpty(strScientistName)) { 
      scientistNameText.setError("Please enter a value"); 
      entriesValid = false; 
     } 
     else if(TextUtils.isEmpty(strScientistEmail)) { 
      scientistEmailText.setError("Please enter a value"); 
      entriesValid = false; 
     } 
     else if(TextUtils.isEmpty(strVolume)) { 
      volumeText.setError("Please enter a value"); 
      entriesValid = false; 
     } 
     else if(TextUtils.isEmpty(strColour)) { 
      colourText.setError("Please enter a value"); 
      entriesValid = false; 
     } 
     } 
     if(entriesValid) 
      dialog.dismiss(); 
     } 
     }); 
     builder.show(); 
     return builder.create(); 
    } 

} 
+0

возможно дубликат [Как для подтверждения ввода текстового ввода в Android?] (http://stackoverflow.com/questions/27788043/how-to-validate-edit-text-input-in-android) – Rohit5k2

+0

@ Rohit5k2 не совсем дубликат, th код отличается от последнего вопроса, его обновляет с помощью проверки ввода, но диалог все же разрешается закрывать, несмотря на булевскую проверку, чтобы предотвратить это. Может ли быть так, что логическое значение никогда не срабатывает, поэтому условие никогда не будет выполнено? –

+0

Я уже ответил, почему ваш диалог закрывается только в последнем вопросе. Boolean не поможет здесь. см. комментарий вашего последнего вопроса. – Rohit5k2

ответ

1

Вместо проверки слушателю быть пустым, добавьте попробовать поймать блок. Я не пробовал этот код. Но моя идея состоит в том, чтобы удалить блок прослушивателя с помощью try catch и соответствующим образом установить логический флаг. Таким образом, это становится простым.

@SuppressLint("NewApi") 
     public static AlertDialog displayMessage(Context context, String title, String message, final MyMessageDialogListener listener){ 
      AlertDialog.Builder builder = new AlertDialog.Builder(context); 
      LayoutInflater inflater = LayoutInflater.from(context); 
      builder.setTitle(title); 
      builder.setMessage(message); 
      final View layoutView = inflater.inflate(R.layout.custom_view, null); 
      builder.setView(layoutView); 
      builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       boolean entriesValid = true; 
       // get the edit text values here and pass them back via the listener 
       try 
       { 
       EditText shipText = (EditText)layoutView.findViewById(R.id.shipNameEditText); 
       EditText scientistNameText = (EditText)layoutView.findViewById(R.id.scientistEditText); 
       EditText scientistEmailText = (EditText)layoutView.findViewById(R.id.emailEditText); 
       EditText volumeText = (EditText)layoutView.findViewById(R.id.volumeEditText); 
       EditText colourText = (EditText)layoutView.findViewById(R.id.colourEditText); 

       String strShipName = shipText.getText().toString(); 
       String strScientistName = scientistNameText.getText().toString(); 
       String strScientistEmail = scientistEmailText.getText().toString(); 
       String strVolume = volumeText.getText().toString(); 
       String strColour = colourText.getText().toString(); 

       if(TextUtils.isEmpty(strShipName)) { 
        shipText.setError("Please enter a value"); 
        entriesValid = false; 
       } 
       else if(TextUtils.isEmpty(strShipName)) { 
        shipText.setError("Please enter a value"); 
        entriesValid = false; 
       } 
       else if(TextUtils.isEmpty(strScientistName)) { 
        scientistNameText.setError("Please enter a value"); 
        entriesValid = false; 
       } 
       else if(TextUtils.isEmpty(strScientistEmail)) { 
        scientistEmailText.setError("Please enter a value"); 
        entriesValid = false; 
       } 
       else if(TextUtils.isEmpty(strVolume)) { 
        volumeText.setError("Please enter a value"); 
        entriesValid = false; 
       } 
       else if(TextUtils.isEmpty(strColour)) { 
        colourText.setError("Please enter a value"); 
        entriesValid = false; 
       } 
       } 
    catch(Exception e) 
    { 
    entriesValid = false; 
    } 
       if(entriesValid) 
        dialog.dismiss(); 
       } 
       }); 
       builder.show(); 
       return builder.create(); 
      } 

обновление - Новое решение - Пробовал и работал для меня

public class Help_DialogScreen extends Dialog implements OnClickListener{ 
Context context; 
    public Help_DialogScreen(Context context) { 
     super(context); 
     // TODO Auto-generated constructor stub 
     this.context=context; 
    } 

    @Override 
     protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(R.layout.help_homescreen); 

     EditText tvGoToAddExpense = (EditText)findViewById(R.id.txtGoToAddExpense); 

     Button btnTestCLick = (Button)findViewById(R.id.btnTestClick); 

     btnTestCLick.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       Toast.makeText(context, "Click fired", Toast.LENGTH_SHORT).show(); 
       // I have used Toast to show that on click of button, dialog is not getting dismissed. You can add your code and do your logic here. 
      } 
     }); 


     } 

    @Override 
    public void onClick(DialogInterface dialog, int which) { 

     dismiss(); 
    } 

} 

В коде, где вы должны показать диалог, добавьте этот код

Help_DialogScreen cdd=new Help_DialogScreen(CURRENTACTIVITY.this); 
       cdd.show(); 
+0

Диалог по-прежнему закрывается с вышеупомянутым исправлением, попробуем что-то в этом роде, http: //stackoverflow.com/questions/4016313/how-to-keep-an -alertdialog-open-after-button-onclick-is-fired –

+0

на основе asynchronustask am, показывающий один alertdailog для запроса имени пользователя без ввода имени, показывает сообщение edittext.setError в поле edittext диалогового окна, но когда я нажимаю ok, вне него введите любое диалоговое окно данных закрывается, пожалуйста, помогите мне – Harsha

Смежные вопросы