简体   繁体   中英

How to show a dialog with Android?

Total noob here. Went through Google's developer reference but didn't find enough detail for me to understand. I am trying to make a dialog box appear when hitting an Action Bar item.

I have 2 classes. The first one is only the DialogFragment, using a AlertDialog builder with a positive button and a negative button.

The 2nd class is the Activity, in which I would like to call my DialogFragment and display the dialog, however I when I try to do that under the OnOptionsItemSelected function, using the following code:

DialogFragment newFragment = new CreateWordListDialog();
            newFragment.show(getSupportFragmentManager(), "createWordList");

I get a "cannot resolve method" line error on the 2nd line. Where should this line be placed? I must be missing something here.

Inside the function OnOptionsItemSelected you can construct your AlertDialog, you don't need to create another class for this.

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.title) //
        .setMessage(R.string.message) //
        .setPositiveButton(getString(R.string.positive), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // TODO
                dialog.dismiss();
            }
        }) //
        .setNegativeButton(getString(R.string.parking_no_button), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // TODO
                dialog.dismiss();
            }
        });
builder.show();

In Android studio android.support.v4 etc are not encluded by default. So either add these dependencies manually or use getFragmentManager() instead of getSupportFragmentManager() and the issue will be solved

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM