Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a NumberPicker on an AlertDialog

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();
}
like image 295
Apodeus Avatar asked Oct 20 '16 19:10

Apodeus


People also ask

What method do you override when displaying a dialog?

Using custom views You can create a DialogFragment and display a dialog by overriding onCreateView() , either giving it a layoutId as you would with a typical fragment or using the DialogFragment constructor. The View returned by onCreateView() is automatically added to the dialog.


2 Answers

You need including 2 lines:

  1. builder.setView(numberPicker);
  2. return build.show()

So, the code must be like this:

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();
}
like image 136
Gláucio Leonardo Sant'ana Avatar answered Oct 09 '22 10:10

Gláucio Leonardo Sant'ana


You never set the view of the Dialog.

builder.setView(numberPicker);
like image 4
OneCricketeer Avatar answered Oct 09 '22 09:10

OneCricketeer