Android应用CardView布局膨胀错误排查求助
Looking at your Logcat output, the root cause jumps right out:
Caused by: android.content.res.Resources$NotFoundException: Can't find ColorStateList from drawable resource ID #0x7f07006e
This error is triggered by a simple mistake in your activity_hschome.xml layout: the card2 CardView uses app:cardBackgroundColor="@drawable/gradient2". The cardBackgroundColor attribute expects a color value or ColorStateList resource, but you’ve passed a gradient drawable instead. Android can’t convert a drawable into a ColorStateList, which causes the layout inflation to fail immediately.
How to Fix It:
- Open
activity_hschome.xmland locate thecard2CardView - Replace
app:cardBackgroundColor="@drawable/gradient2"withandroid:background="@drawable/gradient2"on an inner container (like the LinearLayout inside the CardView), and remove the redundant RelativeLayout that’s covering the background anyway.
Here’s what the corrected card2 should look like:
<androidx.cardview.widget.CardView android:id="@+id/card2" android:layout_width="0dp" android:layout_height="0dp" android:layout_columnWeight="1" android:layout_marginBottom="16dp" android:layout_rowWeight="1" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" app:cardElevation="8dp" app:cardCornerRadius="30dp"> <!-- Removed the unnecessary RelativeLayout, set gradient on the LinearLayout instead --> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center_horizontal|center_vertical" android:layout_margin="16dp" android:background="@drawable/gradient2" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/physics" android:textAlignment="center" android:textColor="#000" android:textSize="18sp" android:textStyle="bold" /> </LinearLayout> </androidx.cardview.widget.CardView>
If you want the gradient to respect the CardView’s rounded corners, create a custom drawable with rounded corners and gradient (using a <shape> tag in a drawable XML file), then apply that to the inner container’s background. This way the gradient won’t bleed outside the CardView’s rounded edges.
Quick Checks to Confirm:
- Make sure your
gradient2drawable has valid syntax (no typos in the gradient definition) - The other CardViews using
android:background="@color/color1"are fine, sincecolor1is a valid color resource
To clear up any confusion: this crash has nothing to do with your OnClickListener setup, JUnit tests, or outdated attributes—it’s purely an incorrect attribute usage that broke resource parsing.
内容的提问来源于stack exchange,提问作者Akshay Raut

