Friday, May 18, 2012

Setting up a dialog template


A real common task is to pop up a confirm/cancel dialog on button clicks.  I've moved this code into a method that I can easily copy and paste into Android Activities and call the dialog with one line of code like the line below. This sample code shows a one button dialog, it's easy to do a two button dialog.  It's easy to set up your custom dialog xml layout which is really similar to any other layout.


showOneButtonDialog(getResources().getString(R.string.errorDialogTitle), message);



 private void showOneButtonDialog(String titleStr, String message) { 

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

                LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

                View layout = inflater.inflate(R.layout.custom_dialog, 

                          (ViewGroup) findViewById(R.id.layout_root)); 

                TextView title = (TextView) layout.findViewById(R.id.headerTitle); 

                title.setText(titleStr); 

                TextView text = (TextView) layout.findViewById(R.id.text); 

                text.setText(message); 

                ImageView image = (ImageView) layout.findViewById(R.id.image); 

                image.setImageResource(R.drawable.ic_launcher); 

                builder.setView(layout); 

                AlertDialog errorDialog = builder.create(); 

                errorDialog.setButton(getResources().getString(R.string.dialogContinue), 

                          new DialogInterface.OnClickListener() { 

                               public void onClick(DialogInterface dialog, int id) { 

                                    dialog.cancel(); 

                               } 

                          }); 

                errorDialog.show(); 

           }