简体   繁体   English

当按下后退按钮时,在Java中调用AlertDialog.Builder for Android Fragment

[英]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. 我是用Fragments做的。 The details portion is a Fragment which has an EditText in it. 细节部分是一个片段,里面有一个EditText 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. 目前,如果用户键入EditText并单击“保存”按钮, AlertDialog.Builder弹出AlertDialog.Builder ,询问她是否要保存。 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: 在我的扩展FragmentActivity课程中,我有:

@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: 在我的课程中扩展Fragment (细节部分),我有:

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 . 我不确定将调用AlertDialog.Builder的代码放在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 ). 我想把它放在Fragment类中,因为代码需要从列表中获取详细信息的rowID (扩展ListFragment的类)。 That information isn't available to the FragmentActivity class. FragmentActivity类无法获得该信息。 For clarification, here's the code I use to operate the Save button. 为了澄清,这是我用来操作Save按钮的代码。 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. 它是从Fragment类的onCreateView方法调用的,我想重新使用这个代码(可能在后面的按钮被击中时把它放在自己的方法中)。

@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: rowID ,当我宣布的二手updateURI来自ListFragment类,如下所示:

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: setRowID在Fragment类中定义:

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

and rowID is a private static int in the Fragment class. rowID是Fragment类中的私有静态int。

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 : OnClickListeners添加到对话框是和否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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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