我制作了一个带有自定义XML属性的覆盖TextView,以便以方便的方式处理此问题。
这也可作为库使用:
https://github.com/rongi/text-view-shadow-dipspublic class TextViewShadowDips extends TextView {
public TextViewShadowDips(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.TextViewShadowDips);
// App can crash on some devices if shadow radius is more than 25 pixels
// On Samsung Galaxy S6 this crash happens when you copy a text from an input field
// https://dev59.com/M1PTa4cB1Zd3GeqPnu5g
final float shadowRadius = Math.min(
attributes.getDimension(R.styleable.TextViewShadowDips_shadowRadius, 0f),
25f
);
final float shadowDx = attributes.getDimension(R.styleable.TextViewShadowDips_shadowDx, 0f);
final float shadowDy = attributes.getDimension(R.styleable.TextViewShadowDips_shadowDy, 0f);
final int shadowColor = attributes.getColor(R.styleable.TextViewShadowDips_shadowColor, 0);
if (shadowColor != 0) {
setShadowLayer(shadowRadius, shadowDx, shadowDy, shadowColor);
} else {
getPaint().clearShadowLayer();
}
attributes.recycle();
}
在“values”资源文件夹中的attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextViewShadowDips">
<attr name="shadowRadius" format="dimension"/>
<attr name="shadowDx" format="dimension"/>
<attr name="shadowDy" format="dimension"/>
<attr name="shadowColor" format="color"/>
</declare-styleable>
</resources>
使用示例:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<my.package.name.TextViewShadowDips
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:shadowColor="#000000"
app:shadowRadius="2dp"
app:shadowDx="2dp"
app:shadowDy="2dp"
/>
</RelativeLayout>