Подтвердить что ты не робот

ColorDrawable нельзя отбрасывать в файл android.support.v7.widget.RoundRectDrawableWithShadow

Проблема, с которой я сталкиваюсь, в основном такова, что находится в этом ответе, но я все равно объясню ниже. Я тестирую устройство с Android 5.0.1, а другое - с 4.2.2. На моем устройстве с 5.0.1 я не получаю ошибок и все ведет себя так, как ожидалось. На моем устройстве 4.2.2 я получаю следующую ошибку:

java.lang.ClassCastException: android.graphics.drawable.ColorDrawable cannot be cast to android.support.v7.widget.RoundRectDrawableWithShadow
        at android.support.v7.widget.CardViewEclairMr1.getShadowBackground(CardViewEclairMr1.java:159)
        at android.support.v7.widget.CardViewEclairMr1.getMinWidth(CardViewEclairMr1.java:150)
        at android.support.v7.widget.CardView.onMeasure(CardView.java:181)
        at android.view.View.measure(View.java:15696)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:681)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
        at android.view.View.measure(View.java:15696)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4851)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at android.view.View.measure(View.java:15696)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4851)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
        at android.view.View.measure(View.java:15696)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4851)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2261)
        at android.view.View.measure(View.java:15696)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2225)
        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1290)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1527)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1190)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4860)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:766)
        at android.view.Choreographer.doCallbacks(Choreographer.java:575)
        at android.view.Choreographer.doFrame(Choreographer.java:542)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:751)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:158)
        at android.app.ActivityThread.main(ActivityThread.java:5751)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1083)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:850)
        at dalvik.system.NativeStart.main(Native Method)

с ошибкой, возникающей в этой строке: card1.setBackgroundColor(getResources().getColor(R.color.White));

Теперь, как было предложено связанным ответом, я попытался использовать setCardBackgroundColor, однако это приводит к возникновению ошибки на обоих моих устройствах. Любые предложения?

КартView, который я пытаюсь использовать, - это android.support.v7.widget.CardView

Это макет, создающий ошибку:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/MainLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#bbbbb5"
android:orientation="vertical"
android:weightSum="100">


<ImageView
    android:id="@+id/imageView"
    android:layout_width="fill_parent"
    android:layout_height="400dp"
    android:layout_gravity="center_vertical|top"
    android:layout_marginBottom="50dp"
    android:layout_marginTop="-65dp"
    android:layout_toRightOf="@+id/prem_BACK"
    android:layout_weight="0"
    android:clickable="true"
    android:paddingBottom="0dp"
    android:src="@drawable/plane1" />


<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/imageView"
    android:layout_alignEnd="@+id/imageView"
    android:layout_alignRight="@+id/imageView"
    android:layout_marginBottom="40dp"
    android:layout_marginRight="5dp"
    android:src="@drawable/ic_navigate_next_white_48dp" />

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view1"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:layout_gravity="center"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="280dp"
    android:clickable="true"
    android:onClick="card1ClickMethod"
    card_view:cardCornerRadius="4dp">

    <TextView
        android:id="@+id/choice_text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:onClick="card1ClickMethod"
        android:text="Loret ipsum sample"
        android:textColor="#212121" />
</android.support.v7.widget.CardView>

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view2"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:layout_gravity="center"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="340dp"
    android:clickable="true"
    android:onClick="card2ClickMethod"
    card_view:cardCornerRadius="4dp">

    <TextView
        android:id="@+id/choice_text2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true"
        android:gravity="center"
        android:onClick="card2ClickMethod"
        android:textColor="#212121" />
</android.support.v7.widget.CardView>

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view3"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:layout_gravity="center"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="400dp"
    android:clickable="true"
    android:onClick="card3ClickMethod"
    card_view:cardCornerRadius="4dp">

    <TextView
        android:id="@+id/choice_text3"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true"
        android:gravity="center"
        android:onClick="card3ClickMethod"
        android:textColor="#212121" />
</android.support.v7.widget.CardView>

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view4"
    android:layout_width="fill_parent"
    android:layout_height="50dp"
    android:layout_gravity="center"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginTop="460dp"
    android:clickable="true"
    android:onClick="card4ClickMethod"
    card_view:cardCornerRadius="4dp">

    <TextView
        android:id="@+id/choice_text4"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true"
        android:gravity="center"
        android:onClick="card4ClickMethod"
        android:textColor="#212121" />
</android.support.v7.widget.CardView>


<TextView
    android:id="@+id/resulttext3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/progressBar1"
    android:layout_alignParentStart="true"
    android:layout_gravity="center_vertical|left"
    android:layout_marginBottom="5dp"
    android:layout_marginLeft="5dp"
    android:textSize="15dp" />

<ProgressBar
    android:id="@+id/progressBar1"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignTop="@+id/fab"
    android:layout_gravity="right|center_vertical"
    android:layout_marginTop="20dp" />

<ImageView
    android:id="@+id/prem_BACK"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_marginLeft="0dp"
    android:layout_marginTop="0dp"
    android:src="@drawable/background4"
    android:visibility="gone" />

После прочтения проблемы описанной здесь, я заметил, что с тех пор она была закрыта. Насколько мне известно, я использую самую обновленную версию инструментов платформы и инструментов sdk, и у меня все еще есть эта проблема.

После некоторого дополнительного тестирования я обнаружил, что эмулятор, который я использую, не имеет GooglePlayServices. В настоящее время у меня нет доступа к физическому устройству с менее чем Android 6.0 для тестирования. Возможно ли, что GooglePlayServices не может вызвать эту проблему?

4b9b3361

Ответ 1

Это работает для меня для cardview внутри recycleview

 ((CardView)viewholder.itemView).setCardBackgroundColor(Color.WHITE);

Ответ 2

Вы также можете сохранить обе версии андроида счастливыми, предоставив им то, что они хотят, а не пытаться заставить и сделать что-то:

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
       // below lillipop
       view.setCardBackgroundColor(Color.WHITE);
       // working for lower questions as per another answer posted here
   } else {
        // lollipop and above
        card1.setBackgroundColor(getResources().getColor(R.color.White));
        // known to be working for lillipop as per your question
}

В основном вызывают разные и рабочие методы для каждой версии Android..

Чтобы правильно идентифицировать версии для Android выше и ниже lollipop, используйте LILLIPOP_MR1 (Soruce)

Ответ 3

Вы можете использовать:

card1.setBackgroundColor(Color.rgb(255, 255, 255));

вместо:

card1.setBackgroundColor(getResources().getColor(R.color.White));

Ответ 4

Самый простой способ сделать то, что вы хотите, это использовать цветной фильтр, я думаю. Я пробовал это на 4.2.2, и он отлично работает.

cardView.getBackground().setColorFilter(Color.BLUE, PorterDuff.Mode.MULTIPLY);

Ответ 5

Используя setBackgroundColor(int color), вы на самом деле вызываете метод на View, переключая фон. CardView ожидает RoundRectDrawableWithShadow, который вы просто перезаписали. Отсюда исключение.

CardView view = (CardView) findViewById(R.id.card);
view.setCardBackgroundColor(Color.RED);

Обязательно вызывайте cardView.setCardBackgroundColor(int), и он работает. Он работает с 4.2.2, и, просматривая исходный код cardView, я уверен и в других apis. Если это также приводит к сбою, это должна быть другая причина.

Ответ 6

Возможно, это разрешено с помощью PublicRoundRectDrawableWithShadow.
Создайте PublicRoundRectDrawableWithShadow.

package android.support.v7.widget;

import android.content.res.Resources;

public class PublicRoundRectDrawableWithShadow extends RoundRectDrawableWithShadow {
    public PublicRoundRectDrawableWithShadow(Resources resources, CardView cardView, int backgroundColor) {
        super(resources, backgroundColor, cardView.getRadius(), cardView.getCardElevation(), cardView.getMaxCardElevation());
    }
}

И setBackground() как это.

    final CardView cardView = (CardView) findViewById(R.id.card_view);
    if (Build.VERSION_CODES.LOLLIPOP <= Build.VERSION.SDK_INT) {
        cardView.setBackgroundColor(Color.RED);
    } else {
        cardView.setBackgroundDrawable(new PublicRoundRectDrawableWithShadow(getResources(), cardView, Color.RED));
    }

Ответ 7

Пожалуйста, попробуйте ниже определенной строки, чтобы установить background color из card view object:

cardView.setCardBackgroundColor(Color.WHITE);