Search code examples
androidandroid-fragmentsdialognumberpicker

Custom layout Dialog with Number Picker


I'm creating a Dialog Fragment with a custom layout which includes a Number Picker.

To do so, I've created a DialogFragment class which implements NumberPicker.onValueChangeListener and a layout xml file that it will use.

I'm having an issue associating the Number Picker in the layout with a variable in the fragment class because 'findViewById' "Method cannot be resolved"

How can I get around this problem?

Elements of code below:

Dialog Fragment:

public class PlayersDialogueFragment extends DialogFragment implements NumberPicker.OnValueChangeListener {

NumberPicker numberOfPlayersPicker = null;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    builder.setView(inflater.inflate(R.layout.players_fragment_layout, null));

    numberOfPlayersPicker = (NumberPicker) findViewById(R.id.numberOfPlayersPicker);
    numberOfPlayersPicker.setMaxValue(4);
    numberOfPlayersPicker.setMinValue(2);

Layout - "players_fragment_layout":

<NumberPicker
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/numberOfPlayersPicker"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

I can put getActivity() before findViewById and can run the app, but it gives a null object reference error by doing so.

PS: If it matters, the dialog fragment is being called by Main Activity upon button press.


Solution

  • Assign inflater.inflate(R.layout.players_fragment_layout, null) to a variable v, and then call v.findViewById like so:

    public class PlayersDialogueFragment extends DialogFragment implements NumberPicker.OnValueChangeListener {
    
        NumberPicker numberOfPlayersPicker = null;
    
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the Builder class for convenient dialog construction
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            LayoutInflater inflater = getActivity().getLayoutInflater();
            View v = inflater.inflate(R.layout.players_fragment_layout, null);
            builder.setView(v);
    
            numberOfPlayersPicker = (NumberPicker) v.findViewById(R.id.numberOfPlayersPicker);
            numberOfPlayersPicker.setMaxValue(4);
            numberOfPlayersPicker.setMinValue(2);
        }
    }