Reputation: 8768
I need to customize a listview's items in the following way. Each item should have a rounded corners and item's background should be adaptively changed according to current system color (either via color filter (PorterDuff) or by calculating color shifts in appropriate rgb components - this stuff is already coded, and this is not the subject of the question, so let us suppose I have a specific color to use as background at runtime).
I can easily apply rounded corners by specifing android:background
in item's layout file which refers to a shape with following code:
<corners android:radius="5dp" />
The problem is, that it's not possible (to my knowledge) to adjust dynamically (from Java) the colors in the shape. So, I can't use the XML-defined shape approach, and I moved to a solution using Java coding.
I have something like that in my getView
method (for the case when background is a color, not a drawable):
PaintDrawable mDrawable = new PaintDrawable();
mDrawable.getPaint().setColor(Color.argb(calcColor, r, g, b));
int px = DP2PX(10);
mDrawable.setCornerRadius(px);
view.setBackgroundDrawable(mDrawable);
It does the thing, but when an item is selected or pressed my custom background overrides default selection background, which is a bug. Selected item must be displayed with standard selection background but with rounded corners.
I've tried to use a subclassed LinearLayout
for listview items and override dispatchDraw
or onDraw
in it, but this strangely has no effect on corners. For example, I found the following code:
float radius = 10.0f;
Path clipPath = new Path();
RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
clipPath.addRoundRect(rect, radius, radius, Path.Direction.CW);
canvas.clipPath(clipPath);
super.dispatchDraw(canvas);
Such custom drawn view is displayed without any changes compared to an item based on standard LinearLayout
.
So, the question is how to combine rounded corners and adaptive background color in a listview item?
Upvotes: 0
Views: 355
Reputation: 8768
I have a partial solution to my problem. The code in getView
is now as follows:
PaintDrawable mDrawable = new PaintDrawable();
mDrawable.getPaint().setColor(Color.argb(calcColor, r, g, b));
int px = DP2PX(10);
mDrawable.setCornerRadius(px);
Drawable defaultBg = getResources().getDrawable(android.R.drawable.list_selector_background);
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed}, defaultBg);
states.addState(new int[] {android.R.attr.state_focused}, defaultBg);
states.addState(new int[] { }, mDrawable);
view.setBackgroundDrawable(states);
This applies rounded corners and custom color for idle views, and shows default selection background for pressed views, but the latter is shown without rounded corners. I'd appreciate any suggestions on how to apply rounded corners on the default selector.
Upvotes: 0