2011-11-23 9 views
80

Si prega di guardare la finestra di dialogo personalizzata qui sotto. Ho un campo di edittext nella finestra di dialogo e se il campo di testo è vuoto vorrei disabilitare lo positiveButton. Posso ottenere un charListener per il campo di testo, ma non sono sicuro di come imposterò lo positivebutton da disabilitare o abilitare da quel listener? Qual è il riferimento per i pulsanti positivi e negativi?Come disabilitare/abilitare i pulsanti positivi negativi della finestra?

case DIALOG_TEXT_ENTRY: 
    // This example shows how to add a custom layout to an AlertDialog 
    LayoutInflater factory = LayoutInflater.from(this); 
    final View textEntryView = factory.inflate(R.layout.alert_dialog_text_entry, null); 
    return new AlertDialog.Builder(AlertDialogSamples.this) 
     .setIconAttribute(android.R.attr.alertDialogIcon) 
     .setTitle(R.string.alert_dialog_text_entry) 
     .setView(textEntryView) 
     .setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int whichButton) { 
       /* User clicked OK so do some stuff */ 
      } 
     }) 
     .setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int whichButton) { 
       /* User clicked cancel so do some stuff */ 
      } 
     }) 
     .create(); 
} 
+0

Penso che questa risposta risponde alla tua domanda [http://stackoverflow.com/questions/4291548/android-alert-dialog -come-a-pelle-the-ok-button-dopo-da-essere-premuto] [1] [1]: http://stackoverflow.com/questions/4291548/android-alert- dialog-how-to-hide-the-ok-button-after-it-being-pressed –

+0

grazie, ma questa non è la risposta. potrebbe aiutare però. perché disabilita il pulsante dopo aver cliccato su se stesso. che non è quello che voglio. Mi piacerebbe mostrarlo disabilitato dipende dal campo di testo. – akd

+1

if (editTextEmailAddress.getText(). ToString(). Length() == 0) – SALMAN

risposta

163

Modifica per soluzione completa ...

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); 
builder.setIcon(android.R.drawable.ic_dialog_info); 
builder.setTitle("Alert dialog title"); 
builder.setMessage("This is the example code snippet to disable button if edittext attached to dialog is empty."); 
builder.setPositiveButton("PositiveButton", 
     new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface arg0, int arg1) { 
       // DO TASK 
      } 
     }); 
builder.setNegativeButton("NegativeButton", 
     new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface arg0, int arg1) { 
       // DO TASK 
      } 
     }); 
// Set `EditText` to `dialog`. You can add `EditText` from `xml` too. 
final EditText input = new EditText(MainActivity.this); 
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCH_PARENT, 
     LinearLayout.LayoutParams.MATCH_PARENT); 
input.setLayoutParams(lp); 
builder.setView(input); 
final AlertDialog dialog = builder.create(); 
dialog.show(); 
// Initially disable the button 
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE) 
     .setEnabled(false); 
// OR you can use here setOnShowListener to disable button at first 
// time. 

// Now set the textchange listener for edittext 
input.addTextChangedListener(new TextWatcher() { 
    @Override 
    public void onTextChanged(CharSequence s, int start, int before, 
      int count) { 
    } 

    @Override 
    public void beforeTextChanged(CharSequence s, int start, int count, 
      int after) { 
    } 

    @Override 
    public void afterTextChanged(Editable s) { 
     // Check if edittext is empty 
     if (TextUtils.isEmpty(s)) { 
      // Disable ok button 
      ((AlertDialog) dialog).getButton(
        AlertDialog.BUTTON_POSITIVE).setEnabled(false); 
     } else { 
      // Something into edit text. Enable the button. 
      ((AlertDialog) dialog).getButton(
        AlertDialog.BUTTON_POSITIVE).setEnabled(true); 
     } 

    } 
}); 

Qui di seguito vengono modificati storia, che può essere riferimento come qualche dettaglio in più

Ecco un codice di esempio, prova questo

AlertDialog.Builder builder = new AlertDialog.Builder(AddSchedule.this); 
builder.setIcon(android.R.drawable.ic_dialog_info); 
builder.setTitle("Alert dialog title"); 
builder.setMessage("Dialog message"); 
builder.setPositiveButton("Button1", new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface arg0, int arg1) { 
     //DO TASK 
    } 
}); 
builder.setNegativeButton("Button2", new DialogInterface.OnClickListener() { 
    public void onClick(DialogInterface arg0, int arg1) { 
     //DO TASK 
    } 
}); 

AlertDialog dialog = builder.create(); 
dialog.show(); 

//After calling show method, you need to check your condition and 
//enable/ disable buttons of dialog 
if(your_condition_true) 
    dialog.getButton(AlertDialog.BUTTON1).setEnabled(false); //BUTTON1 is positive button 

Per pulsante negativa

dialog.getButton(AlertDialog.BUTTON2).setEnabled(false); //BUTTON2 is negative button 

Per i pulsanti id: Riferimentoalert_dialog.xml

Edited:

E il setOnShowListener dal livello 8 API (Froyo), fa la stessa cosa,

AlertDialog.Builder builder = new AlertDialog.Builder(this); 
builder.setPositiveButton(android.R.string.ok, null); 
AlertDialog dialog = builder.create(); 
dialog.setOnShowListener(new OnShowListener() { 

    @Override 
    public void onShow(DialogInterface dialog) { 
     if(condition) 
     ((AlertDialog)dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); 
    } 
}); 

dialog.show(); 

A cura

new AlertDialog.Builder(this) 
    .setMessage("This may take a while") 
    .setPositiveButton("OK", new android.content.DialogInterface.OnClickListener() { 
    @Override 
    public void onClick(DialogInterface dialog, int which) { 
     ((AlertDialog)dialog).getButton(which).setVisibility(View.INVISIBLE); 
     // the rest of your stuff 
    } 
}) 
    .show(); 

+0

correggimi se ho torto ma quando hai chiamato di nuovo AlertDialog si chiama di nuovo il suo oggetto o lo usa ancora. Non sono a conoscenza di questo metodo. Spiegheresti in breve? Grazie :) – NovusMobile

+0

Per gli skimmer vorrei aggiungere che dialog.getButton() funziona solo con AlertDialogs, quindi potresti dover lanciare la finestra di dialogo in AlertDialog mentre lo fai più avanti nel post. – Noumenon

+0

non funziona - anche io ho letto codice almeno 5x, e non ha ancora senso perché dovrebbe funzionare :) La risposta corretta è qui sotto di Nick Palmer – qkx

-1
if(editTextEmailAddress.getText().toString().length()==0) 
{ 
btnCancelCross.setEnabled(false); 
} 
else 
{ 
btnCancelCross.setEnabled(true); 

} 

che potrebbero aiutarvi, grazie.

+0

grazie, ma questo non è quello che sto cercando. Posso farlo usando la finestra di dialogo personalizzata e creare un layout con il pulsante e abilitarli disabilitarli. Quello che sto cercando è che c'è un modo per disabilitare o abilitare i pulsanti di dialogo positivi e negativi? Se guardi il codice che ho condiviso vedrai quello che sto cercando. Ma grazie ancora per il codice. – akd

+2

Per favore, postare _one_ esauriente sulla risposta all'argomento (basta modificare la risposta esistente, non continuare a postare risposte aggiuntive). –

+1

Come leggere l'id del pulsante di dialogo? –

18

Nessuna di queste risposte davvero risolvere il problema.

Realizzo ciò utilizzando un layout personalizzato con un testo Edit in esso e un TextWatcher su quella vista.

final LinearLayout layout = (LinearLayout) inflator.inflate(R.layout.text_dialog, null); 
final EditText text = (EditText) layout.findViewById(R.id.text_edit); 
final AlertDialog.Builder builder = new AlertDialog.Builder(this); 
builder.setView(layout); 
// Now add the buttons... 
builder.setPositiveButton(R.string.ok, new AlertDialog.OnClickListener() { 
    // Left out for brevity... 
} 
builder.setNegativeButton(R.string.cancel, new AlertDialog.OnClickListener() { 
    // Left out for brevity... 
} 
// Now add a TextWatcher that will handle enable/disable of save button 
text.addTextChangedListener(new TextWatcher() { 
    private void handleText() { 
     // Grab the button 
     final Button okButton = d.getButton(AlertDialog.BUTTON_POSITIVE); 
     if(text.getText().length() == 0) { 
      okButton.setEnabled(false); 
     } else { 
      okButton.setEnabled(true); 
     } 
    } 
    @Override 
    public void afterTextChanged(Editable arg0) { 
     handleText(); 
    } 
    @Override 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
     // Nothing to do 
    } 
    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) { 
     // Nothing to do 
    } 
}); 
// Create the dialog 
AlertDialog d = builder.create(); 
// show the dialog 
d.show(); 
// and disable the button to start with 
d.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); 
+0

in realtà la tua risposta è corretta :) Grazie – qkx

+0

Questa risposta è incompleta, non c'è la dichiarazione di 'd' – user3175580

+0

Modificato per aggiungere la costruzione di d. –

0

per il record di eliminazione dalla visualizzazione elenco database utilizzando vista titolare si è utilizzato questo codice nel metodo() GetView ..

viewHolder.btn.setOnClickListener (nuova OnClickListener() {

   @Override 
       public void onClick(View arg0) { 
        // TODO Auto-generated method stub 
        AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
          Favorate.this.getParent()); 

        // Setting Dialog Title 
        alertDialog2.setTitle("Confirm Delete..."); 

        // Setting Dialog Message 
        alertDialog2 
          .setMessage("Are you sure you want delete ?"); 

        // Setting Icon to Dialog 
        alertDialog2.setIcon(R.drawable.delete); 

        // Setting Positive "Yes" Btn 
        alertDialog2.setPositiveButton("YES", 
          new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, 
             int which) { 
            // Write your code here to execute after 
            // dialog 

            int id = _items.get(position).id; 
            db.deleterecord(id); 

            db.close(); 
           } 
          }); 
        // Setting Negative "NO" Btn 
        alertDialog2.setNegativeButton("NO", 
          new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, 
             int which) { 
            // Write your code here to execute after 
            // dialog 

            dialog.cancel(); 
           } 
          }); 

        // Showing Alert Dialog 
        alertDialog2.show(); 

       } 
      }); 

Read More

0

Questa dialogFragment farà il lavoro per voi. Si noti che la finestra di dialogo rimarrà aperta dopo la rotazione dello schermo conservando qualsiasi testo che l'utente ha già digitato . Se non si desidera che ciò accada è necessario respingere il frammento nel onStop della vostra attività. il metodo di firma newInstance può essere cambiato in qualsiasi cosa avete bisogno.

import android.app.Activity; 
import android.app.Dialog; 
import android.app.DialogFragment; 
import android.content.DialogInterface; 
import android.os.Bundle; 
import android.support.annotation.Nullable; 
import android.support.v7.app.AlertDialog; 
import android.text.Editable; 
import android.text.TextWatcher; 
import android.widget.EditText; 

public class TextViewDialogFragment extends DialogFragment implements DialogInterface.OnClickListener, DialogInterface.OnShowListener, TextWatcher 
{ 
    final static private String TITLE = "title", MESSAGE = "message", IDENTIFIER = "identifier", INPUT_TYPE = "inputType", POSITIVE_TEXT = "pText", NEGATIVE_TEXT = "nText", CANCELABLE = "cancelable"; 

    public TextViewDialogFragment() 
    { 
     super(); 
    } 

    static public TextViewDialogFragment newInstance(int title, @Nullable String message, int identifier, int inputType, int positiveText, int negativeText, boolean cancelable) 
    { 
     TextViewDialogFragment fragement = new TextViewDialogFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(TITLE, title); 
     args.putString(MESSAGE, message); 
     args.putInt(IDENTIFIER, identifier); 
     args.putInt(INPUT_TYPE, inputType); 
     args.putInt(POSITIVE_TEXT, positiveText); 
     args.putInt(NEGATIVE_TEXT, negativeText); 
     args.putBoolean(CANCELABLE, cancelable); 
     fragement.setArguments(args); 
     return fragement; 
    } 

    @Override 
    public Dialog onCreateDialog(Bundle savedInstanceState) 
    { 
     Activity activity = getActivity(); 
     Bundle args = getArguments(); 
     EditText input = new EditText(activity); 
     input.setInputType(args.getInt(INPUT_TYPE)); 
     input.setId(R.id.dialog_edit_text); 
     input.addTextChangedListener(this); 
     AlertDialog.Builder alert = new AlertDialog.Builder(activity); 
     alert.setCancelable(args.getBoolean(CANCELABLE)).setTitle(args.getInt(TITLE)).setMessage(args.getString(MESSAGE)).setView(input).setPositiveButton(args.getInt(POSITIVE_TEXT), this); 
     int negativeText = args.getInt(NEGATIVE_TEXT); 
     if (negativeText != 0) 
     { 
      alert.setNegativeButton(negativeText, this); 
     } 
     AlertDialog dialog = alert.create(); 
     dialog.setOnShowListener(this); 
     return dialog; 
    } 

    @Override 
    public void onShow(DialogInterface dialog) 
    { 
     // After device rotation there may be some text present. 
     if (((EditText)((AlertDialog) dialog).findViewById(R.id.dialog_edit_text)).length() == 0) 
     { 
      ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); 
     } 
    } 

    @Override 
    public void onClick(DialogInterface dialog, int which) 
    { 
     String text = ((EditText)((AlertDialog) dialog).findViewById(R.id.dialog_edit_text)).getText().toString(); 
     ((Callbacks) getActivity()).onTextViewDialogResult(which, getArguments().getInt(IDENTIFIER), text); 
    } 

    @Override 
    public void onCancel(DialogInterface dialog) 
    { 
     ((Callbacks) getActivity()).onTextViewDialogActivityCancelled(getArguments().getInt(IDENTIFIER)); 
     super.onCancel(dialog); 
    } 

    @Override 
    public void beforeTextChanged(CharSequence s, int start, int count, int after) 
    { 
    } 

    @Override 
    public void onTextChanged(CharSequence s, int start, int before, int count) 
    { 
    } 

    @Override 
    public void afterTextChanged(Editable s) 
    { 
     ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(s.length() > 0); 
    } 

    void setMessage(String message) 
    { 
     Bundle args = getArguments(); 
     args.putString(MESSAGE, message); 
     setArguments(args); 
    } 

    interface Callbacks 
    { 
     void onTextViewDialogResult(int which, int identity, String text); 
     void onTextViewDialogActivityCancelled(int identity); 
    } 
} 

Add implementa alla vostra attività (qualsiasi tipo di attività va bene):

public class Myctivity extends AppCompatActivity implements TextViewDialogFragment.Callbacks 
{ 
... 
} 

Creare il diaglogFragment nella vostra attività come questo:

final static int SOMETHING = 1; 
myDF = TextViewDialogFragment.newInstance(R.string.my_title, "my message", SOMETHING, InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES, /* Whatever is best for your user. */ R.string.yay, android.R.string.cancel, true); 

gestire il risultato nella vostra attività come questo:

@Override 
public void onTextViewDialogResult(int which, int identity, String text) 
{ 
    if (which == AlertDialog.BUTTON_NEGATIVE) 
    { 
     // User did not want to do anything. 
     return; 
    } 
    // text now holds the users answer. 
    // Identity can be used if you use the same fragment for more than one type of question. 
} 
@Override 
public void onTextViewDialogActivityCancelled(int identity) 
{ 
    // This is invoked if you set cancelable to true and the user pressed the back button. 
} 

È necessario creare l'identificatore di risorsa in modo da aggiungere questa risorsa da qualche parte sotto res/values ​​

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <item name="dialog_edit_text" type="id"/> 
</resources> 
2

Ecco il codice completo per abilitare e disabilitare il pulsante positivo di dialogo

AlertDialog.Builder builder = new AlertDialog.Builder(this); 

    LayoutInflater layoutInflater = MainActivity.this.getLayoutInflater(); 

    View view = layoutInflater.inflate(R.layout.dialog,null); 

    builder.setView(view); 

    builder.setTitle("Test"); 
    builder.setPositiveButton("ok", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 

      Toast.makeText(MainActivity.this, "Ok clicked", Toast.LENGTH_SHORT).show(); 
      dialog.dismiss(); 

     } 
    }); 
    builder.setNegativeButton("cancel", null); 


    final AlertDialog alertDialog = builder.create(); 

    alertDialog.show(); 

    EditText editText = (EditText)view.findViewById(R.id.mobile_number); 
    alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); 
    editText.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

     } 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 

     } 

     @Override 
     public void afterTextChanged(Editable s) { 

      if(s.length()>=1) 
      { 
       alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true); 
      } 
      else { 
       alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false); 

      } 

     } 
    }); 
Problemi correlati