【问题标题】:Change Raduis CardView Background Color更改半径 CardView 背景颜色
【发布时间】:2021-04-26 06:28:06
【问题描述】:

我有一个带有半径和描边的 CardView,但是当我以编程方式更改 CardView 背景时,半径和描边丢失了,我希望新颜色留在描边内。

这是我的卡片视图 xml

<com.google.android.material.card.MaterialCardView
      android:id="@+id/answerOneTransport"
      android:layout_width="148dp"
      android:layout_height="60dp"
      android:layout_marginStart="32dp"
      android:layout_marginTop="32dp"
      app:cardBackgroundColor="#F7F7F7"
      app:cardCornerRadius="16dp"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/quizzTransportViewPager"
      app:strokeColor="#9890FF"
      app:strokeWidth="1dp" >
      <TextView
          android:id="@+id/textAnswwerOneTransport"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Answer One"
          android:layout_gravity="center"
          android:fontFamily="@font/nunito"
          android:textSize="20sp"
          />
  </com.google.android.material.card.MaterialCardView> 

这是我改变颜色的地方:

answerOneTransport.setOnClickListener {
    answerOneTransport.setBackgroundColor(Color.GREEN)
}

【问题讨论】:

    标签: android xml android-layout android-cardview cardview


    【解决方案1】:

    要改变CardView的背景颜色你必须使用方法:

    cardView.setCardBackgroundColor(ContextCompat.getColor(this,R.color.xxx));
    

    【讨论】:

    • 为什么要添加 ContextCompat ?
    • @AnasHafidi 这是一种从支持不同API的资源中获取颜色的简单方法
    【解决方案2】:

    你需要使用 android:backgroundTint

    【讨论】:

    • 您能否通过一些细节改进您的答案?
    猜你喜欢
    • 2018-08-19
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 2017-09-19
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多