开发者

Dismiss android preferences dialog on Keyboard ACTION_DONE press

I would like to be able to close the editpreference dialog (as shown here http://twitpic.com/18ttdp) by pressing the 'Done' button on the keyboard.

Currently, pressing 'Done' just dismisses the keyboard but leaves the dialog.

In other parts of my application I use code similar to the following to intercept the 'Done' key press and execute actions in my activity:

text.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                //do stuff here
                return true;
            }
            return false;
        }
    });

However, I am unsure of how to do achieve this same effect开发者_StackOverflow中文版 in my preference activity or layout xml.


Instead of adding the listener there, you should do something similar to this:

getDialog().setOnKeyListener(new OnKeyListener() {

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        dialog.dismiss();
        return true;
    }
});

This code will dismiss the dialog when a key is pressed.


I had the same problem, this is how I solved it:

    // edit text to get input
    final EditText input = new EditText(this);
    //input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
    input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_IME_MULTI_LINE);
    alert.setView(input);

    // ok button
    alert.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // do stuff
        }
    });

For my needs, the input was a number (hence the commented out line) but if you want text use what's there.


Here is how I solved it:

    final EditTextPreference namePref = (EditTextPreference) findPreference("name");
    namePref.getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if(actionId == EditorInfo.IME_ACTION_DONE) {
                namePref.onClick(null, DialogInterface.BUTTON_POSITIVE);
                namePref.getDialog().dismiss();
                return true;
            }
            return false;
        }
    });

But you may want to consider subclassing EditTextPreference instead, since this onClick call is a hack, and its implementation may change in the future.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜