Simples fragments de dialog sim / não

Gostairia de fazer um dialog fragment que pergunta "Você tem certeza?" com uma resposta "sim / não".

Eu examinei a documentation e é realmente detalhado, indo por todo o lado, explicando como fazer checkboxs de dialog avançadas, mas nenhum código intacto paira criair um tipo de checkbox de dialog simples do "mundo olá". A maioria dos tutoriais utiliza o sistema de checkbox de dialog desativado. O blog oficial pairece ser desnecessairiamente complicado e difícil de entender.

  • SIGILL no código NDK do Android
  • Android HoneyComb DatePicker Cor do text
  • Android LineairLayout fill-the-middle
  • como otimizair renderspeed na webview do Android
  • Motor de jogo Android NDK
  • Enviair notificação paira todos os dispositivos conectados a uma networking Wi-Fi
  • Então, qual é a maneira mais simples de criair e exibir uma checkbox de dialog de alerta realmente básica? Pontos de bônus se estiview usando a biblioteca de suporte.

  • Existe uma maneira de impedir que o AlertDialog feche com inputs inválidas?
  • ID de registro duplicado do Android paira diferentes dispositivos
  • Fazendo o upload de uma image do Android (com o Cliente Http asynchronous Android) paira o server de rails (com clipe de papel)
  • Códigos de erro GCM
  • Obtendo `Erro: Não é possível obter propriedade ': lib' on null object` em um novo projeto do Android Studio
  • O método setCancelable (falso) do AlertDialog não está funcionando
  • 4 Solutions collect form web for “Simples fragments de dialog sim / não”

    Um DialogFragment é realmente apenas um fragment que envolve uma checkbox de dialog. Você pode colocair qualquer tipo de dialog lá, criando e retornando a checkbox de dialog no método onCreateDialog () do DialogFragment.

    Seu exemplo: DialogFragment:

     class MyDialogFragment extends DialogFragment{ Context mContext; public MyDialogFragment() { mContext = getActivity(); } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext); alertDialogBuilder.setTitle("Really?"); alertDialogBuilder.setMessage("Are you sure?"); //null should be your on click listener alertDialogBuilder.setPositiveButton("OK", null); alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } } } class MyDialogFragment extends DialogFragment{ Context mContext; public MyDialogFragment() { mContext = getActivity(); } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext); alertDialogBuilder.setTitle("Really?"); alertDialogBuilder.setMessage("Are you sure?"); //null should be your on click listener alertDialogBuilder.setPositiveButton("OK", null); alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } } } class MyDialogFragment extends DialogFragment{ Context mContext; public MyDialogFragment() { mContext = getActivity(); } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext); alertDialogBuilder.setTitle("Really?"); alertDialogBuilder.setMessage("Are you sure?"); //null should be your on click listener alertDialogBuilder.setPositiveButton("OK", null); alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } } }); class MyDialogFragment extends DialogFragment{ Context mContext; public MyDialogFragment() { mContext = getActivity(); } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext); alertDialogBuilder.setTitle("Really?"); alertDialogBuilder.setMessage("Are you sure?"); //null should be your on click listener alertDialogBuilder.setPositiveButton("OK", null); alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } } } class MyDialogFragment extends DialogFragment{ Context mContext; public MyDialogFragment() { mContext = getActivity(); } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(mContext); alertDialogBuilder.setTitle("Really?"); alertDialogBuilder.setMessage("Are you sure?"); //null should be your on click listener alertDialogBuilder.setPositiveButton("OK", null); alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } } 

    Paira criair a chamada de dialog:

     new MyDialogFragment().show(getFragmentManager(), "MyDialog"); 

    E paira descairtair o dialog de algum lugair:

     ((MyDialogFragment)getFragmentManager().findFragmentByTag("MyDialog")).getDialog().dismiss(); 

    Todo esse código funcionairá perfeitamente com a biblioteca de suporte, apenas alterando as importações paira usair as classs da biblioteca de suporte.

    Então, qual é a maneira mais simples de criair e exibir uma checkbox de dialog de alerta realmente básica? Pontos de bônus se estiview usando a biblioteca de suporte.

    Basta criair um DialogFragment (sdk ou biblioteca de suporte) e replace o método onCreateDialog paira retornair um AlertDialog com o text desejado e os botões definidos nela:

     public static class SimpleDialog extends DialogFragment { @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setMessage("Are you sure?").setPositiveButton("Ok", null) .setNegativeButton("No way", null).create(); } } } public static class SimpleDialog extends DialogFragment { @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setMessage("Are you sure?").setPositiveButton("Ok", null) .setNegativeButton("No way", null).create(); } } 

    Paira fazer algo quando o user usa um dos botões, você terá que fornecer uma instância de DialogInterface.OnClickListener vez das references null do meu código.

    Paira aqueles que codificam com Kotlin e Anko , agora você pode fazer checkboxs de dialog em 4 linhas de código:

     alert("Order", "Do you want to order this item?") { positiveButton("Yes") { processAnOrder() } negativeButton("No") { } }.show() 

    Por causa do ciclo de vida da atividade / Fragmento, a abordagem @athor & @lugsprog pode crashr, uma maneira mais elegante é ** obter o context da atividade do método onAttach e airmazená-lo como reference fraca ** (e tentair evitair o construtor não padrão no DialogFragment !, passair qualquer airgumento paira dialogair airgumentos de uso) assim:

     public class NotReadyDialogFragment extends DialogFragment { public static String DIALOG_ARGUMENTS = "not_ready_dialog_fragment_airguments"; private WeakReference<Context> _contextRef; public NotReadyDialogFragment() { } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { /** example pulling of airguments */ Bundle bundle = getArguments(); if (bundle!=null) { bundle.get(DIALOG_ARGUMENTS); } // // Caution !!! // check we can use contex - by call to isAttached // or by checking stored weak reference value itself is not null // or stored in context -> example allowCreateDialog() // - then for example you could throw illegal state exception or return null // AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(_contextRef.get()); alertDialogBuilder.setMessage("..."); alertDialogBuilder.setNegativeButton("Przerwij", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); _contextRef = new WeakReference<Context>(activity); } boolean allowCreateDialog() { return _contextRef !== null && _contextRef.get() != null; } } public class NotReadyDialogFragment extends DialogFragment { public static String DIALOG_ARGUMENTS = "not_ready_dialog_fragment_airguments"; private WeakReference<Context> _contextRef; public NotReadyDialogFragment() { } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { /** example pulling of airguments */ Bundle bundle = getArguments(); if (bundle!=null) { bundle.get(DIALOG_ARGUMENTS); } // // Caution !!! // check we can use contex - by call to isAttached // or by checking stored weak reference value itself is not null // or stored in context -> example allowCreateDialog() // - then for example you could throw illegal state exception or return null // AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(_contextRef.get()); alertDialogBuilder.setMessage("..."); alertDialogBuilder.setNegativeButton("Przerwij", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); _contextRef = new WeakReference<Context>(activity); } boolean allowCreateDialog() { return _contextRef !== null && _contextRef.get() != null; } } public class NotReadyDialogFragment extends DialogFragment { public static String DIALOG_ARGUMENTS = "not_ready_dialog_fragment_airguments"; private WeakReference<Context> _contextRef; public NotReadyDialogFragment() { } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { /** example pulling of airguments */ Bundle bundle = getArguments(); if (bundle!=null) { bundle.get(DIALOG_ARGUMENTS); } // // Caution !!! // check we can use contex - by call to isAttached // or by checking stored weak reference value itself is not null // or stored in context -> example allowCreateDialog() // - then for example you could throw illegal state exception or return null // AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(_contextRef.get()); alertDialogBuilder.setMessage("..."); alertDialogBuilder.setNegativeButton("Przerwij", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); _contextRef = new WeakReference<Context>(activity); } boolean allowCreateDialog() { return _contextRef !== null && _contextRef.get() != null; } } public class NotReadyDialogFragment extends DialogFragment { public static String DIALOG_ARGUMENTS = "not_ready_dialog_fragment_airguments"; private WeakReference<Context> _contextRef; public NotReadyDialogFragment() { } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { /** example pulling of airguments */ Bundle bundle = getArguments(); if (bundle!=null) { bundle.get(DIALOG_ARGUMENTS); } // // Caution !!! // check we can use contex - by call to isAttached // or by checking stored weak reference value itself is not null // or stored in context -> example allowCreateDialog() // - then for example you could throw illegal state exception or return null // AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(_contextRef.get()); alertDialogBuilder.setMessage("..."); alertDialogBuilder.setNegativeButton("Przerwij", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); _contextRef = new WeakReference<Context>(activity); } boolean allowCreateDialog() { return _contextRef !== null && _contextRef.get() != null; } }); public class NotReadyDialogFragment extends DialogFragment { public static String DIALOG_ARGUMENTS = "not_ready_dialog_fragment_airguments"; private WeakReference<Context> _contextRef; public NotReadyDialogFragment() { } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { /** example pulling of airguments */ Bundle bundle = getArguments(); if (bundle!=null) { bundle.get(DIALOG_ARGUMENTS); } // // Caution !!! // check we can use contex - by call to isAttached // or by checking stored weak reference value itself is not null // or stored in context -> example allowCreateDialog() // - then for example you could throw illegal state exception or return null // AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(_contextRef.get()); alertDialogBuilder.setMessage("..."); alertDialogBuilder.setNegativeButton("Przerwij", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); _contextRef = new WeakReference<Context>(activity); } boolean allowCreateDialog() { return _contextRef !== null && _contextRef.get() != null; } } public class NotReadyDialogFragment extends DialogFragment { public static String DIALOG_ARGUMENTS = "not_ready_dialog_fragment_airguments"; private WeakReference<Context> _contextRef; public NotReadyDialogFragment() { } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { /** example pulling of airguments */ Bundle bundle = getArguments(); if (bundle!=null) { bundle.get(DIALOG_ARGUMENTS); } // // Caution !!! // check we can use contex - by call to isAttached // or by checking stored weak reference value itself is not null // or stored in context -> example allowCreateDialog() // - then for example you could throw illegal state exception or return null // AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(_contextRef.get()); alertDialogBuilder.setMessage("..."); alertDialogBuilder.setNegativeButton("Przerwij", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); _contextRef = new WeakReference<Context>(activity); } boolean allowCreateDialog() { return _contextRef !== null && _contextRef.get() != null; } } public class NotReadyDialogFragment extends DialogFragment { public static String DIALOG_ARGUMENTS = "not_ready_dialog_fragment_airguments"; private WeakReference<Context> _contextRef; public NotReadyDialogFragment() { } @Oviewride public Dialog onCreateDialog(Bundle savedInstanceState) { /** example pulling of airguments */ Bundle bundle = getArguments(); if (bundle!=null) { bundle.get(DIALOG_ARGUMENTS); } // // Caution !!! // check we can use contex - by call to isAttached // or by checking stored weak reference value itself is not null // or stored in context -> example allowCreateDialog() // - then for example you could throw illegal state exception or return null // AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(_contextRef.get()); alertDialogBuilder.setMessage("..."); alertDialogBuilder.setNegativeButton("Przerwij", new DialogInterface.OnClickListener() { @Oviewride public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); return alertDialogBuilder.create(); } @Oviewride public void onAttach(Activity activity) { super.onAttach(activity); _contextRef = new WeakReference<Context>(activity); } boolean allowCreateDialog() { return _contextRef !== null && _contextRef.get() != null; } 

    EDIT: e se você deseja descairtair a checkbox de dialog, então:

    1. tente obtê-lo
    2. viewifique se existe
    3. viewifique se está mostrando
    4. dispensair

    algo assim :

      NotReadyDialogFragment dialog = ((NotReadyDialogFragment) getActivity().getFragmentManager().findFragmentByTag("MyDialogTag")); if (dialog != null) { Dialog df = dialog.getDialog(); if (df != null && df.isShowing()) { df.dismiss(); } } }  NotReadyDialogFragment dialog = ((NotReadyDialogFragment) getActivity().getFragmentManager().findFragmentByTag("MyDialogTag")); if (dialog != null) { Dialog df = dialog.getDialog(); if (df != null && df.isShowing()) { df.dismiss(); } } 

    EDIT2: & se você quiser configurair a checkbox de dialog como não cancelável, você deve alterair a declairação de return onCreatweDialog como esta:

      /** conviewt builder to dialog */ AlertDialog alert = alertDialogBuilder.create(); /** disable cancel outside touch */ alert.setCanceledOnTouchOutside(false); /** disable cancel on press back button */ setCancelable(false); return alert; 
    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.