Android: How to use NumberPickerDialog

2019-04-16 21:41发布

问题:

Could someone give me an example of how to instantiate a NumberPickerDialog within Activity.onCreateDialog ?(https://github.com/novak/numberpicker/blob/master/lib/src/com/michaelnovakjr/numberpicker/NumberPickerDialog.java) ?

There are examples in a repo called numberpicker-demo for using the widget, but none for the actual dialog.

Amongst other approaches I've tried tried something like:

return new NumberPickerDialog.Builder(this)
    .setTitle("Choose Number")
    .etc..

But this just shows a standard AlertDialog, without the NumberPicker.

Thanks!

回答1:

Got it working eventually. There's an example in com.quietlycoding.android.picker.Picker, but I've found that the dialog doesn't set the dimming properly, blacking out the whole Activity in the background while it's in view.

I worked around this by simply creating an AlertDialog in the usual way, and then just sticking a NumberPicker widget into setView():

LayoutInflater inflater = (LayoutInflater)
    getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View npView = inflater.inflate(R.layout.number_picker_pref, null);
    return new AlertDialog.Builder(this)
        .setTitle("Text Size:")
        .setView(npView)
        .setPositiveButton(R.string.dialog_ok,
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                }
            })
            .setNegativeButton(R.string.dialog_cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                })
            .create();

Make sure to copy number_picker_pref.xml from the numberpicker project to res/layout in your own project.



回答2:

Look at this (and optionaly this: Creating dialogs).



回答3:

That should be much simpler if only you do this:

  1. Add NumberPicker to you layout
  2. Add this code on your Activity

        //charger le NumberPicker
        npicker = (NumberPicker) findViewById(R.id.picker);
        // Set intervalle
        npicker.setRange(1, pages.size());
        // Set la valeur actuelle
        npicker.setCurrent(1);
    
        npicker.setOnChangeListener(new OnChangedListener() {               
            @Override
            public void onChanged(NumberPicker picker, int oldVal, int newVal) {
                // TODO Auto-generated method stub
                Log.e("Log Change event","oldVal: "+oldVal+"//newVal: "+newVal);
            }
        });