4

我有一种在代码中创建 RippleDrawables 的方法

    public class StateApplier {    

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
        private static void add_Ripple(Resources res, StateListDrawable states
                , int color, int pressedColor){
            Drawable rd = new android.graphics.drawable.RippleDrawable(get_Ripple_ColorSelector(pressedColor)
                    , new ColorDrawable(color), null);
            states.addState(new int[] {}, rd);

        }

当我在 Lollipop 上运行它时效果很好,但是当我在 KitKat 设备上运行它时,它崩溃了。这是错误日志。

03-12 21:36:47.734: E/dalvikvm(26295): Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method com.acme.applib.Render.StateApplier.add_Ripple
03-12 21:36:47.734: W/dalvikvm(26295): VFY: unable to resolve new-instance 149 (Landroid/graphics/drawable/RippleDrawable;) in Lcom/acme/applib/Render/StateApplier;
03-12 21:36:47.734: D/dalvikvm(26295): VFY: replacing opcode 0x22 at 0x0000
03-12 21:36:47.738: W/dalvikvm(26295): VFY: unable to find class referenced in signature (Landroid/graphics/drawable/RippleDrawable;)
03-12 21:36:47.738: W/dalvikvm(26295): VFY: returning Ljava/lang/Object; (cl=0x0), declared Landroid/graphics/drawable/Drawable; (cl=0x0)
03-12 21:36:47.738: W/dalvikvm(26295): VFY:  rejecting opcode 0x11 at 0x0004
03-12 21:36:47.738: W/dalvikvm(26295): VFY:  rejected Lcom/acme/applib/Render/StateApplier;.create_Ripple (Landroid/content/res/Resources;II)Landroid/graphics/drawable/Drawable;
03-12 21:36:47.738: W/dalvikvm(26295): Verifier rejected class Lcom/acme/applib/Render/StateApplier;

我认为使用 @TargetApi(Build.VERSION_CODES.LOLLIPOP)会强制在低于棒棒糖的设备上跳过代码。奇怪的是,甚至不调用方法 add_Ripple() 而是调用 StateApplier 类中的另一个方法的活动崩溃了。

注意在调用方法之前我也在使用 api 检查

if( Build.VERSION.SDK_INT >=  Build.VERSION_CODES.LOLLIPOP){
add_Ripple(res, states, color, pressedColor);

什么是在较新的 API 中引用类而不在旧设备上崩溃的适当方法。

4

1 回答 1

3

我所做的是创建另一个名为StateApplierLollipop的类,并将所有处理RippleDrawable的代码移到那里,StateApplier 中的代码只会在 StateApplierLollipop 中为 Lollipop+ 设备调用该代码。这阻止了 KitKat 上的崩溃。

public class StateApplierLollipop {  
public static void add_Ripple(Resources res, StateListDrawable states
                , int color, int pressedColor){
    ...........
   }
}

public class StateApplier{
public static void add_Ripple(Resources res, StateListDrawable states
                    , int color, int pressedColor){
if( Build.VERSION.SDK_INT >=  Build.VERSION_CODES.LOLLIPOP){
   StateApplierLollipop.add_Ripple(....

}

于 2015-07-18T03:56:38.263 回答