2014-01-03 4 views
1

Если у меня есть alertdialog, и у меня есть две кнопки: «OK» и «cancel», где alertdialog состоит только из поля editText, как я могу его создать, чтобы «OK» разрешал пользователю продолжить, если вход не равен нулю?AlertDialog Onclick

Например, если ввод является нулевым, а пользователь нажимает «ОК», он будет запрашивать тост, но не отменит диалог оповещений? У меня возникла проблема, когда, если ввод пуст, и они нажимают «ОК», alertdialog закрывается.

+0

Сообщение код вашего метода OnClick() в OK пресс-обработчика. – jagmohan

ответ

1

Для AlertDialog с EditText вы должны создать и AlertDialog с настраиваемое представление. Тогда Ok и Cancel будут просто логикой.

Для этого я должен создать файл пользовательского макета:

пользовательского макета XML:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="#AEAAEE" 
    android:orientation="vertical" > 

    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="50dp" 
     android:layout_marginLeft="10dp" 
     android:layout_marginRight="10dp" 
     android:layout_marginTop="10dp" 
     android:background="#9A9A9F" 
     android:gravity="center" 
     android:text="Please input character" 
     android:textColor="#FFFFFF" 
     android:textSize="17sp" /> 

    <EditText 
     android:id="@+id/edittext" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:hint="input" /> 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" > 

     <Button 
      android:id="@+id/cancelButton" 
      android:layout_width="0dp" 
      android:layout_height="wrap_content" 
      android:layout_marginTop="10dp" 
      android:layout_weight="1" 
      android:text="Cancel" 
      android:textColor="#FFFFFF" /> 

     <Button 
      android:id="@+id/okbutton" 
      android:layout_width="0dp" 
      android:layout_weight="1" 
      android:layout_marginTop="10dp" 
      android:layout_height="wrap_content" 
      android:text="OK" 
      android:textColor="#FFF" /> 
    </LinearLayout> 

</LinearLayout> 

заказного макета Java файла:

public class CustomDialog extends Dialog implements android.view.View.OnClickListener{ 

     public Activity c; 
     public Dialog d; 
     public Button cancelButton, okButton; 
     public EditText input; 

     public CustomDialog(Activity a) { 
     super(a); 
     // TODO Auto-generated constructor stub 
     this.c = a; 
     } 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(R.layout.custom_dialog); 
     okButton = (Button)findViewById(R.id.okbutton); 
     input = (EditText)findViewById(R.id.edittext); 
     cancelButton = (Button)findViewById(R.id.cancelButton); 
     okButton.setOnClickListener(this); 
     cancelButton.setOnClickListener(this); 

     } 

     @Override 
     public void onClick(View v) { 
     switch (v.getId()) { 
     case R.id.okbutton: 
      String value = input.getText().toString(); 
      if(value.length()<0){ 
       Toast.makeText(c.getApplicationContext(), "No input", Toast.LENGTH_SHORT).show(); 
      } 
      break; 
     case R.id.cancelButton: 
      dismiss(); 
      break; 
     default: 
     break; 
     } 
     dismiss(); 
     } 

} 

На ссылке:

CustomDialog dialog = new CustomDialog(activity); 
dialog.show(); 
1

Для этого нужно создать настраиваемое диалоговое окно. Пожалуйста, посмотрите на этот пример Android Prompt User Input Dialog Example. Если вход является нулевым или пробелом "" не отменяет оповещение Простой.

0
AlertDialog.Builder alert = new AlertDialog.Builder(this); 
alert.setTitle("TITLE HERE"); 
alert.setMessage("MESSAGE"); 

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int whichButton) { 
    String str = editext.getText().toString().trim(); //Your edittext 
//Do something here where "ok" clicked 
    if(str != null && !str.isEmpty()) 
    { 

     } 
    else 
    { 
    Toast.makeText(getApplicationContext(), "PLease Enter Value",Toast.LENGTH_LONG).show(); 
    } 
    }); 
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface dialog, int whichButton) { 
    //So sth here when "cancel" clicked. 
} 
}); 
alert.show(); 
0

на onclicklistener кнопку ОК, в

if (editext.getText().toString().trim().isEmpty()) 
//show toast 
else 
//proceed 
0

Я не знаю ни одного способа справиться с этой короткой сделать подкласс AlertDialog и вручную обработки входной логики. В качестве альтернативы вы можете проверить значение в EditText и отобразить другое диалоговое окно с сообщением об ошибке? Или вы можете попробовать отключить кнопку до тех пор, пока вход в EditText не будет действительным, установив прослушиватель в EditText.

Хотя все эти варианты действительно просто работают вокруг, что должно быть простым пользовательским диалогом.

0

Используйте это:

Activity temp = this; 

& сейчас в Уре использования кода

AlertDialog.Builder nointernetconnection = new AlertDialog.Builder(
     temp); 
nointernetconnection 
     .setIcon(R.drawable.logo) 
     .setTitle("No Internet Connection") 
     .setMessage(
       "You don't have an internet connection...") 
     .setCancelable(true) 
     .setPositiveButton("OK", 
       new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface arg, 
          int arg1) { 
         //finish(); 
         } 
       }); 
AlertDialog a = nointernetconnection.create(); 
a.show(); 
0

Это очень просто.Это, как я сделал:

создать свой prompts.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/layout_root" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" 
android:padding="10dp" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Enter Backup Name: " 
    android:textAppearance="?android:attr/textAppearanceLarge" /> 

<EditText 
    android:id="@+id/editTextDialogUserInput" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 

    <requestFocus /> 

</EditText> 

</LinearLayout> 

Затем

внутри onClick() вашего зрения:

LayoutInflater li = LayoutInflater.from(this); 
    View promptsView = li.inflate(R.layout.prompts, null); 

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); 
    alertDialogBuilder.setView(promptsView); 

    final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput); 

    // alertDialogBuilder.setCancelable(false); //optional 

    alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() 
                { 
                 public void onClick(DialogInterface dialog,int id) 
                 { 
                  if(userInput.getText()+"" != "") 
                  { 
                   Intent i = new Intent(MainActivity.this,AskForTextFile.class); 
                   i.putExtra("userInput",userInput.getText()+""); 
                   startActivity(i); 
                  } 
                  else 
                  { 
                   Toast.makeText(context, "Please enter backup name to go further.", Toast.LENGTH_LONG).show(); 
                  } 

                 } 
                } 
             ); 

    alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
                 { 
                  public void onClick(DialogInterface dialog,int id) 
                  { 
                   dialog.cancel(); 
                  } 
                 } 
             ); 

    AlertDialog alertDialog = alertDialogBuilder.create(); 
    alertDialog.show(); 
1

Использование Android Пользовательский диалог. И для кнопки и edittext используйте код ниже.

Код:

alertDialogBuilder 
         .setCancelable(false) 
         .setPositiveButton("OK", 
           new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, 
              int id) { 
             // get user input and set it to result 
             // edit text 
             if (editext.length() == 0) { 
              Toast t = Toast 
                .makeText(
                  getApplicationContext(), 
                  "write something in edittext", 
                  Toast.LENGTH_LONG); 
              t.show(); 
             } else { 
              Toast.makeText(
                getApplicationContext(), 
                "You clicked on OK", 
                Toast.LENGTH_SHORT).show(); 
              dialog.cancel(); 
             } 
            } 
           }) 
         .setNegativeButton("Cancel", 
           new DialogInterface.OnClickListener() { 
            public void onClick(DialogInterface dialog, 
              int id) { 
             dialog.cancel(); 
            } 
           }); 

       // create alert dialog 
       AlertDialog alertDialog = alertDialogBuilder.create(); 

       // show it 
       alertDialog.show(); 

      } 

     }); 
Смежные вопросы