Custom CardView context.obtainStyledAttributes not working

Viewed 14

I'm trying to custom Android CardView by using the following code:

@SuppressLint("CustomViewStyleable")
class HotCommentView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : CardView(context, attrs, defStyleAttr) {

    private var binding: LayoutHotCommentBinding

    init {
        binding = LayoutHotCommentBinding.inflate(LayoutInflater.from(context), this, true)

        val typedArray = context.obtainStyledAttributes(attrs, androidx.cardview.R.styleable.CardView, defStyleAttr, androidx.cardview.R.style.CardView)
        cardElevation = typedArray.getDimension(androidx.cardview.R.styleable.CardView_cardElevation, 0f)
        
        typedArray.recycle()
    }
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#f6f6f6"
    app:cardCornerRadius="5dp"
    app:cardElevation="0dp">

</androidx.cardview.widget.CardView>

However the cardElevation="0dp" and other attributes like corner radius are also not working at all, the card still have elevation. And I tried to print out the value of the typedArray.getDimension expression, it all returns 2.5 which was unexpected. Maybe CardView is unextendable or am I doing wrong?

0 Answers
Related