I have an AlertDialog
with just some text, a NumberPicker
, an OK, and a Cancel.
package org.dyndns.schep.example;
import android.os.Bundler;
import android.view.View;
import android.widget.NumberPicker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
public class FooFragment extends DialogFragment {
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mParent = (MainActivity) activity;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
mParent.setFoo(foo());
}
})
.setNegativeButton(android.R.string.cancel, null);
View view = getActivity().getLayoutInflater.inflate(
R.layout.dialog_foo, null);
mPicker = (NumberPicker) view.findViewById(R.id.numberPicker1);
mPicker.setValue(mParent.getFoo());
builder.setView(view);
return builder.create();
}
public int foo() {
return mPicker.getValue();
}
private MainActivity mParent;
private NumberPicker mPicker;
}
(This dialog doesn't yet do the things it should to preserve state on Pause and Resume, I know.)
I would like the "Done" action on the soft keyboard or other IME to dismiss the dialog as though "OK" were pressed, since there's only the one widget to edit.
It looks like the best way to deal with an IME "Done" is usually to setOnEditorActionListener
on a TextView
. But I don't have any TextView
variable, and NumberPicker
doesn't obviously expose any TextView
, or similar editor callbacks. (Maybe NumberPicker
contains a TextView
with a constant ID I could search for using findViewById
?)
NumberPicker.setOnValueChangedListener
does get triggered on the "Done" action, but it also fires when tapping or flicking the list of numbers, which definitely should not dismiss the dialog.
Based on this question, I tried checking out setOnKeyListener
, but that interface didn't trigger at all when using the soft keyboard. Not a total surprise, since the KeyEvent
documentation suggests it's meant more for hardware events, and in recent APIs the soft keyboard won't send them at all.
How can I connect the IME "Done" to my dialog's "OK" action?
Edit: From the looks of the source, a NumberPicker
layout does contain a EditText
, but its id is id/numberpicker_input
in package com.android.internal
. Using that would not be easy, and is obviously discouraged. But it seems like there might only be hack ways to get the behavior I want.