简体   繁体   中英

Calling AlertDialog.Builder in Java For Android Fragment When Back Button Is Pressed

I have a simple application (really!) that displays a list and then displays the details of an item on the list based on the user's choice. I do this using Fragments. The details portion is a Fragment which has an EditText in it. Currently, if the user types in the EditText and clicks on the Save button, an AlertDialog.Builder pops up asking her if she wants to save. If she chooses yes, the text is saved to a database. I want the same thing to happen if the user hits the back button. In my class that extends FragmentActivity , I have:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{

    super.onKeyDown(keyCode, event);

    DetailFrag frag = (DetailFrag) getSupportFragmentManager().findFragmentById(R.id.frag_stitchdetail);
    frag.onKeyDown(keyCode, event);
    return false;
}

In my class that extends Fragment (the details portion), I have:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_ENTER && event.getRepeatCount() == 0
            && Edited) {
        return true;
    }
    else
        return false;
}

I'm not sure where to put the code that will call the AlertDialog.Builder . I want to put it in the Fragment class because the code needs to get the rowID of the detail from the list (a class that extends ListFragment ). That information isn't available to the FragmentActivity class. For clarification, here's the code I use to operate the Save button. It's called from the onCreateView method of the Fragment class and I want to re-use this code (put it in its own method, probably) when the back button is hit.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.detailfragment, container, false);
    Typeface danielFont = Typeface.createFromAsset(getActivity().getAssets(),
            "danielbk.ttf");

    final EditText notes = (EditText)view.findViewById(R.id.stitchnotes);
    notes.setTypeface(danielFont);
    notes.setTextSize(12);

    builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Do you want to save your Notes?");
    builder.setCancelable(false);

    builder.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {

                    String Notes = notes.getText().toString();
                    Uri updateUri = ContentUris.withAppendedId(STITCHES_URI, rowID);
                    ContentValues values = new ContentValues();
                    values.put("stitchnotes", Notes);
                    getActivity().getContentResolver().update(updateUri,values,null,null);
                }
            });

    builder.setNegativeButton("No",
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    //getActivity().finish();
                }
            });

    alert = builder.create();

    ImageButton savebutton = (ImageButton)view.findViewById(R.id.savebutton);
    savebutton.setOnClickListener(new ImageButton.OnClickListener() {

        public void onClick(View v) {
            alert.show();
        }
    });
    notes.addTextChangedListener(new TextWatcher() {

        @Override
        public void afterTextChanged(Editable s) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start,
                int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start,
                int before, int count) {
            Edited = true;

        }
    });

    return view;
}

The rowID that's used when I declare updateURI comes from the ListFragment class like so:

DetailFrag frag = (DetailFrag) getFragmentManager().findFragmentById(R.id.frag_stitchdetail);
if (frag != null && frag.isInLayout()) {
     //more code
     frag.setRowID(stitchid);
}

setRowID is defined in the Fragment class:

public void setRowID(int row_id)
{
    rowID = row_id;
}

and rowID is a private static int in the Fragment class.

Can someone please point me in the right direction?

Two options I can see.

One:

public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if(keyCode == KeyEvent.KEYCODE_BACK) {
        backPressed = true;
        alert.show();
        return true; // shows you consumed the event with your implementation
    }
    // blah, blah, other code
}

Add the following lines to your dialog yes and no OnClickListeners :

if (backPressed){
    finish();// - to exit the Activity
}

Alternately, create two separate builders as follows:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // other code

    builder = new AlertDialog.Builder(getActivity());
    builder.setMessage("Do you want to save your Notes?");
    builder.setCancelable(false);

    builder.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    saveNotes();
                }
            });

    builder.setNegativeButton("No",
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    alertSave = builder.create();


    builder.setPositiveButton("Yes",
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    saveNotes();
                    finish();
                }
            });

    builder.setNegativeButton("No",
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    finish();
                }
            });

    alertBack = builder.create();

    ImageButton savebutton = (ImageButton)view.findViewById(R.id.savebutton);
    savebutton.setOnClickListener(new ImageButton.OnClickListener() {

        public void onClick(View v) {
            alertSave.show();
        }
    });
    // other code
}

public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if(keyCode == KeyEvent.KEYCODE_BACK) {
        alertBack.show();
        return true; // shows you consumed the event with your implementation
    }
    // blah, blah, other code
}        


private void saveNotes() {
    String Notes = notes.getText().toString();
    Uri updateUri = ContentUris.withAppendedId(STITCHES_URI, rowID);
    ContentValues values = new ContentValues();
    values.put("stitchnotes", Notes);
    getActivity().getContentResolver().update(updateUri,values,null,null);
}

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