Android: How to use NumberPickerDialog

2019-04-16 21:46发布

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!

3条回答
相关推荐>>
2楼-- · 2019-04-16 22:22

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);
            }
        });
    
查看更多
孤傲高冷的网名
3楼-- · 2019-04-16 22:24

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

查看更多
Root(大扎)
4楼-- · 2019-04-16 22:25

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.

查看更多
登录 后发表回答