Search code examples
androidandroid-viewandroid-seekbar

Why progress changed is not called?


I'm extending SeekBar:

public class NutritionalSeekBar extends SeekBar implements SeekBar.OnSeekBarChangeListener {

    public NutritionalSeekBar(Context context) {
        super(context);
    }

    public NutritionalSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NutritionalSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public NutritionalSeekBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        progress = (Math.round(progress / 50)) * 50;
        seekBar.setProgress(progress);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
}

Then use it in xml:

<com.package.views.NutritionalSeekBar
    android:id="@+id/seek_bar_carbos"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:progress="50" />

Why the callback progress changed is never called?


Solution

  • If you want a NutritionalSeekBar instance to be its own OnSeekBarChangeListener, you have to set it as such. You should also chain your constructors. For example:

    public class NutritionalSeekBar extends SeekBar implements SeekBar.OnSeekBarChangeListener {
    
        public NutritionalSeekBar(Context context) {
            this(context, null);
        }
    
        public NutritionalSeekBar(Context context, AttributeSet attrs) {
            this(context, attrs, 0);
        }
    
        public NutritionalSeekBar(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
    
            setOnSeekBarChangeListener(this);
        }
        ...
    
    }