Sunday 7 December 2014

Dialog

In the Android tutorial, it gives some examples to Instantiate AlertDialog.Builder like this.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
But getActivity() is a method of the Fragment class, can not apply to everywhere. 

The correct way to do it is use
AlertDialog.Builder builder = new AlertDialog.Builder(this);
or when calling from an inner class, use
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
MainActivity here is your main activity name.

This is one example how to build a single selection dialog.
    private String[]fruits = new String[]{"荔枝","葡萄","栗子","西瓜"};
    private TextView dia_schsres = null;
protected void onCreateDialog() {
                Dialog schDia = new AlertDialog.Builder(ExampleActivity.this);     //AlertDialog.Builder or AlertDialog or Dialog
                    schDia.setIcon(R.drawable.ic_launcher).setTitle("Background").
                        setItems(fruits,new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dia, int which) {
                                dia_schsres.setText(fruits[which]);
                            }
                        }).setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dia, int which) {
                        dia.dismiss();
                    }
                }).create();
}

No comments:

Post a Comment