1.佈局
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<android.support.v7.widget.LinearLayoutCompat
android:id="@+id/linear_layout"
android:layout_width="match_parent"
android:layout_margin="20dp"
android:layout_height="300dp"
android:gravity="center">
<android.support.v7.widget.AppCompatTextView
android:id="@+id/tv_test"
android:layout_width="100dp"
android:layout_height="100dp" />
</android.support.v7.widget.LinearLayoutCompat>
</android.support.v7.widget.LinearLayoutCompat>
2.效果
3.代碼
linearLayout.setBackground(ShapeUtil.drawViewShape(this,50f,20f,R.color.green,R.color.black));
tvTest.setBackground(ShapeUtil.drawViewShape(this,50f,2f,R.color.white,R.color.red));
4.工具類
public class ShapeUtil {
/**
* @param context
* @param roundRadius 圓角大小
* @param strokeWidth 線寬度
* @param fillColorId 填充色
* @param strokeColorId 線顏色
* @return
*/
public static GradientDrawable drawViewShape(Context context, Float roundRadius, Float strokeWidth, int fillColorId, int strokeColorId) {
int strokeColor = 0;
if (strokeColorId > 0) {
//邊線顏色
strokeColor =ContextCompat.getColor(context, strokeColorId);
}
//創建drawable
GradientDrawable gd = new GradientDrawable();
//內部填充顏色
if (fillColorId > 0) {
gd.setColor(ContextCompat.getColor(context, fillColorId));
}
gd.setCornerRadius(DisplayUtil.dipToPix(context, roundRadius));
if (strokeWidth > 0 && strokeColor != 0) {
gd.setStroke((int) DisplayUtil.dipToPix(context, strokeWidth), strokeColor);
}
return gd;
}
}
public class DisplayUtil {
/**
* 根據dip值轉化成px值
*
* @param context
* @param dip
* @return
*/
public static float dipToPix(Context context, float dip) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, context.getResources().getDisplayMetrics());
}
}
class ShapeUtil {
companion object {
fun drawViewShape(context: Context, roundRadius: Float, strokeWidth: Float,
fillColorId: Int, strokeColorId: Int): GradientDrawable {
var strokeColor = 0
if (strokeColorId > 0) {
strokeColor = ContextCompat.getColor(context, strokeColorId)
}
val gd = GradientDrawable()
if (fillColorId > 0) {
gd.setColor(ContextCompat.getColor(context, fillColorId))
}
gd.cornerRadius = DisplayUtil.dipToPx(context, roundRadius)
if (strokeWidth > 0 && strokeColor != 0) {
gd.setStroke((DisplayUtil.dipToPx(context, strokeWidth)).toInt(), strokeColor)
}
return gd
}
}
}
class DisplayUtil {
companion object {
fun dipToPx(context: Context, dip: Float): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, context.resources.displayMetrics)
}
}
}
這樣就不用寫煩人的Drawable了!告辭!