我創建重寫帶有自定義xml屬性的TextView以便捷的方式處理這個問題。
public class TextViewShadowDips extends TextView {
public TextViewShadowDips(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.TextViewShadowDips);
final float shadowRadius = attributes.getDimension(R.styleable.TextViewShadowDips_shadowRadius, 0f);
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();
}
}
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="2dip"
app:shadowDx="2dip"
app:shadowDy="2dip"
/>
</RelativeLayout>
行,沒問題。 – user291701 2011-01-31 19:30:19
陰影參數的單位是什麼?是px,pt,dp,sp ...? – 2012-09-02 09:57:55
如果沒有指定,那麼單位總是在px。 – 2012-09-04 16:27:49