Emily Emily - 1 month ago 25
Android Question

GradientDrawable's setStroke

This is my first time to ask question in stackoverflow, now I'm confused about GradientDrawable's stroke width,when I use code to set TextView backgroud as following

GradientDrawable gd = new GradientDrawable();
gd.setShape(GradientDrawable.RECTANGLE);
gd.setColor(fillColor);
gd.setCornerRadius(roundRadius);
int strokeColor = Color.parseColor(getColor(Subject.list.get(0).color));
gd.setStroke(strokeWidth, strokeColor);
tvSpecial1Title.setText(Subject.list.get(0).title);
tvSpecial1Title.setTextColor(strokeColor);
tvSpecial1Title.setBackgroundDrawable(gd);
tvSpecial1Intro.setText(Subject.list.get(0).intro);


the result of this method is that the stroke width of the TextView is thinner than use XML,and the XML is defined as following

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#00ffffff" />
<stroke
android:width="0.5dp"
android:color="#ff8200" />
<corners android:radius="2dp" />
<padding
android:bottom="1dp"
android:left="3dp"
android:right="3dp"
android:top="1dp" />


</shape>


using the XML as following

TextView t = new TextView(getContext());
t.setBackgroundResource(R.drawable.plugin_movie_item_icon_orange_selector);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.rightMargin = CommonUtils.dip2px(5);
t.setLayoutParams(params);
t.setGravity(Gravity.CENTER);
t.setIncludeFontPadding(false);
t.setSingleLine();
t.setTextColor(Color.parseColor("#ff8200"));
t.setTextSize(10);`


these two kinds of method to set stroke width led to different images in visually, the former stroke width is thinner than the latter,Is there anybody help solve this problem,more hearty thanks to you.

Answer

Wrap your applyDemensions method inside a Math.round().

Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, strokeWidth, getResources().getDisplayMetrics()));