Search code examples
onclicklistenernumberpicker

Having trouble making onClick() work with NumberPicker


I am using a number picker which is defined like this:

<NumberPicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:id="@+id/numberPickerCompoundView" />

The purpose of this number picker is to appear when the user clicks on the TextView to help them change the value of the textview without using the virtual keyboard. In my class that extends a LinearLayout, I use the following code to capture the click on the TextView and make the Number Picker appear:

mTextView.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View view) {
            if(mNumberPicker.getVisibility()==View.VISIBLE){
                mNumberPicker.setVisibility(View.GONE);
            } else {
                mNumberPicker.setVisibility(View.VISIBLE);
            }
            setValue(mTextView.getText().toString());
        }
    });

and then use the following code to add the onClickListener to the Number Picker

mNumberPicker=(NumberPicker)findViewById(R.id.numberPickerCompoundView);
mNumberPicker.setMaxValue(9);
mNumberPicker.setValue(mCurrentValue);
mNumberPicker.setClickable(true);
mNumberPicker.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(), "Click Captured", Toast.LENGTH_SHORT).show();
                if (view == mNumberPicker){
                    mNumberPicker.setVisibility(View.GONE);
                    setValue(Integer.toString(mNumberPicker.getValue()));
                    mTextView.setVisibility(View.VISIBLE);

                }

            }
        });

However, when I click on the Number Picker, it just keeps rolling the values but does not enter the onClick() method. Could someone please help.


Solution

  • NumbePicker uses click to change its value. You can add your logic to OnValueChangeListener.onValueChange().

    Maybe, you should only hide the picker if (newValue == oldValue).