Search code examples
androidlinear-gradientsandroid-seekbar

Getting exact color code from LinearGradient in android SeekBar


I have a requirement in my project to create SeekBar filled with different shades of color. For that purpose, I am using LinearGradient by assigning start and end color value and it is also works like charm. But I have no idea how to get the exact color code from the seekbar when the position changes.

I am also posting some piece of code for your reference:

public class SeekbarActivity extends Activity {

    private SeekBar volumeControl = null;
    private View view;
    private ShapeDrawable shape;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_seekbar);

        volumeControl = (SeekBar) findViewById(R.id.volume_bar);

        view = (View) findViewById(R.id.seek_view);

        LinearGradient test = new LinearGradient(0.f, 0.f, 300.f, 0.0f,
                Color.BLACK, Color.RED, TileMode.CLAMP);

        shape = new ShapeDrawable(new RectShape());
        shape.getPaint().setShader(test);

        volumeControl.setProgressDrawable((Drawable) shape);

        volumeControl.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {

            }

            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub
            }

            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

    }

} 

Output image

enter image description here


Solution

  • There is no default options available to get the color shades using seekbar, but some calculations with the color code will give you the result. This is how I have done to get color shades using a seekbar

    seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int a = Color.alpha(selectedColor);
                int r = Color.red(selectedColor);
                int g = Color.green(selectedColor);
                int b = Color.blue(selectedColor);
                int rr = (progress*r)/100;
                int gg = (progress*g)/100;
                int bb = (progress*b)/100;
                colorView.setBackgroundColor(Color.argb(a, rr, gg, bb));
    
            }
    
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
    
            }
    
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
    
            }
        });