james
james

Reputation: 157

Exit app dialog from a fragment

I would like to prompt users to exit the app using the on back pressed, However I am struggling to implement this in my fragment

public class HomeFragment extends Fragment {


    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                        HomeFragment.super.onBackPressed();
                    }
                }).create().show();
    }
}

Upvotes: 0

Views: 2047

Answers (3)

Kashif Anwaar
Kashif Anwaar

Reputation: 798

You can't do that inside Fragments, but it's possible in your situation as every fragment runs on some Activity.

Just put that onBackPressed code on the activity which contains fragment.

Upvotes: 1

Manish
Manish

Reputation: 334

use this code for showing alert dialog box

   final android.support.v7.app.AlertDialog.Builder alertDialog = new android.support.v7.app.AlertDialog.Builder(getActivity());
        alertDialog.setTitle("Your text");
        alertDialog.setMessage("Your custom text")
                .setCancelable(true).setPositiveButton("Rate Us", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                //your custom toast 
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        }).create().show();

    }

Upvotes: 1

MRX
MRX

Reputation: 1442

Can you try this way and check if it works :

@Override
public void onDetach() {
    super.onDetach();
    PUT YOUR CODE HERE
}

Upvotes: 0

Related Questions