小编D4d*_*4rk的帖子

android.graphics.drawable.ColorDrawable无法强制转换为android.support.v7.widget.RoundRectDrawableWithShadow

我尝试在我的应用程序中使用CardView,它在我的xml布局中工作得很好.由于我想在我的代码中生成它们而不是通过xml,我尝试使用CardView.setRadius()设置半径 - Android开发人员建议的方法(https://developer.android.com/preview/material/ui-widgets .html #cardview).

这根本不起作用!我希望有人可以帮助我解决我的问题,或者通过xml布局得到一个很好的解决方法.

这是我的代码:

int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, getResources().getDisplayMetrics());
        float radius = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());

        for (String color : colors) {
            CardView card = new CardView(getActivity());
            TextView text = new TextView(getActivity());
            card.setBackgroundColor(Color.parseColor("#"+color));
            card.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, height));
            card.setRadius(radius); //Error!!
            text.setText(args.get(colors.indexOf(color)) + " - #" + color);
            card.addView(text);
            group.addView(card);
        }
Run Code Online (Sandbox Code Playgroud)

这是我的日志:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.brobox.materialcolorpalette/com.brobox.materialcolorpalette.MainActivity}: java.lang.ClassCastException: android.graphics.drawable.ColorDrawable cannot be cast to android.support.v7.widget.RoundRectDrawableWithShadow
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102) …
Run Code Online (Sandbox Code Playgroud)

android android-appcompat android-cardview

50
推荐指数
3
解决办法
2万
查看次数