Programmatically create Parallelogram Drawable in Android

I am trying to recreate a toggle switch that is visible in Ice Cream Sandwich but not available for Android versions below ICS. I am at a point where I like my slider, however currently I am using two images with parallelograms (one for its state, one for its state). I would ideally create a drawable at runtime and just change its color based on state. This will ultimately help with the setup.

I am new to drawables in general and would like to create this programmatically, since we do not use xml in our framework.

The reason for this is that the parallelogram is one separate part, which makes scaling much more manageable and customizable.

Any help would be greatly appreciated, and please let me know if you need more information!

This is what android looks like, I would like to simulate mine after them: ICS Toggle

If you need any other details, please let me know, I hope that I will explain what I need in a meaningful way.

Thanks!

+4
source share
1 answer

So, I was able to answer it myself ... I used the paths to create the drawings, and then stitched them together to create a parallelogram.

public Drawable createThumbDrawable(boolean checked){ Path path = new Path(); path.moveTo(0, 0); path.lineTo(1, 0); path.lineTo(1, 1); path.lineTo(0, 1); path.close(); PathShape shape = new PathShape(path, 1, 1); ShapeDrawable drawable = new ShapeDrawable(shape); if (checked){ drawable.getPaint().setColor(Color.CYAN); } else { drawable.getPaint().setColor(Color.BLACK); } mThumbLeftDrawable = createLeftThumbDrawable(checked); mThumbRightDrawable = createRightThumbDrawable(checked); return drawable; } public Drawable createLeftThumbDrawable(boolean checked){ Path path = new Path(); path.moveTo(0, 25); path.lineTo(25, 0); path.lineTo(25, 25); path.close(); PathShape shape = new PathShape(path, 25, 25); ShapeDrawable drawable = new ShapeDrawable(shape); if (checked){ drawable.getPaint().setColor(Color.CYAN); } else { drawable.getPaint().setColor(Color.BLACK); } return drawable; } public Drawable createRightThumbDrawable(boolean checked){ Path path = new Path(); path.moveTo(0,0); path.lineTo(25, 0); path.lineTo(0, 25); path.close(); PathShape shape = new PathShape(path, 25, 25); ShapeDrawable drawable = new ShapeDrawable(shape); if (checked){ drawable.getPaint().setColor(Color.CYAN); } else { drawable.getPaint().setColor(Color.BLACK); } return drawable; } public void setChecked(boolean checked) { //Log.d(TAG, "setChecked("+checked+")"); boolean lc = checked; if (!mTextOnThumb) { lc = !checked; } if (checked){ mThumbDrawable = createThumbDrawable(checked);//this.getContext().getResources().getDrawable(R.drawable.slide_off); } else { mThumbDrawable = createThumbDrawable(checked);//this.getContext().getResources().getDrawable(R.drawable.slide); } super.setChecked(checked); mThumbPosition = lc ? getThumbScrollRange() : 0; invalidate(); } 
+5
source

All Articles