Display a NumberPicker on an AlertDialog

时间:2016-10-20 19:02:40

标签: android alertdialog numberpicker

I am trying to display a NumberPicker on an AlertDialog.
The AlertDialog works, but it doesn't show the NumberPicker.

Here is my code

public Dialog onCreateDialog(Bundle savedInstanceState){
    final NumberPicker numberPicker = new NumberPicker(getActivity());
    numberPicker.setMaxValue(360);
    numberPicker.setMinValue(0);


    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Changing the Hue");
    builder.setMessage("Choose a value :");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialogHost.onPositiveButton(numberPicker.getValue());
        }
    });
    builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialogHost.onCancelButton();
        }
    });
    return builder.create();
}

2 个答案:

答案 0 :(得分:4)

您需要包含两行:

  1. builder.setView(numberPicker);
  2. return build.show()
  3. 所以,代码必须是这样的:

    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        final NumberPicker numberPicker = new NumberPicker(getActivity());
        numberPicker.setMaxValue(360);
        numberPicker.setMinValue(0);
    
    
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(numberPicker);    
        builder.setTitle("Changing the Hue");
        builder.setMessage("Choose a value :");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    
        @Override
        public void onClick(DialogInterface dialog, int which) 
        {
            dialogHost.onPositiveButton(numberPicker.getValue());
        }
        });
        builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which) 
        {
            dialogHost.onCancelButton();
        }
        });
       builder.create();
       return builder.show();
    }
    

答案 1 :(得分:2)

You never set the view of the Dialog.

builder.setView(numberPicker);