检查当前的Android API后,验证错误

时间:2016-02-29 09:10:55

标签: android

我有以下TestActivity

public class TestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Button button = new Button(this);
            button.setBackground(getPressedColorRippleDrawable(Color.RED, Color.BLACK));
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public static RippleDrawable getPressedColorRippleDrawable(int normalColor, int pressedColor) {
        return new RippleDrawable(ColorStateList.valueOf(pressedColor), getColorDrawableFromColor(normalColor), getColorDrawableFromColor(normalColor));
    }

    public static ColorDrawable getColorDrawableFromColor(int color) {
        return new ColorDrawable(color);
    }
}

此代码在Lollipop设备上运行良好,但在较旧的Android API上,即使创建Application,我也会遇到以下异常:

E/AndroidRuntime: FATAL EXCEPTION: main
 java.lang.VerifyError: TestActivity
     at java.lang.Class.newInstanceImpl(Native Method)
     at java.lang.Class.newInstance(Class.java:1215)
     at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2255)
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
     at android.app.ActivityThread.access$800(ActivityThread.java:151)
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
     at android.os.Handler.dispatchMessage(Handler.java:110)
     at android.os.Looper.loop(Looper.java:193)
     at android.app.ActivityThread.main(ActivityThread.java:5299)
     at java.lang.reflect.Method.invokeNative(Native Method)
     at java.lang.reflect.Method.invoke(Method.java:515)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
     at dalvik.system.NativeStart.main(Native Method)

我知道API< RippleDrawable不可用21但不是条件Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP应该解决这个问题吗?

1 个答案:

答案 0 :(得分:5)

我自己修好了。 Java不喜欢带有返回类的方法签名,在这种情况下是RippleDrawable,它并不知道。解决方案是在我的Drawable方法中返回getPressedColorRippleDrawable()

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static Drawable getPressedColorRippleDrawable(int normalColor, int pressedColor) {
    return new RippleDrawable(ColorStateList.valueOf(pressedColor), getColorDrawableFromColor(normalColor), getColorDrawableFromColor(normalColor));
}