Android: How to keep corner radius while setting a background drawable?

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

<android.support.v7.widget.CardView    xmlns:android="http://schemas.android.com/apk/res/android"   xmlns:card_view="http://schemas.android.com/apk/res-auto"   android:id="@+id/card_view"   android:layout_width="match_parent"   android:layout_height="wrap_content"   android:layout_margin="@dimen/activity_vertical_margin"   card_view:cardCornerRadius="12dp"   card_view:cardElevation="12dp">      <LinearLayout     android:layout_width="match_parent"     android:layout_height="wrap_content"     android:orientation="vertical">      .....  </android.support.v7.widget.CardView> 

This is what I set in layout.xml

I'd like to programmatically change the background of the card at runtime.

CardView card =(CardView) findViewById(R.id.card_view); card.setBackgroundResource(R.drawable.card1); 

This will set all radius corners to 0dp. I'd like to keep the radius and the background drawable.

回答1:

Instead of CardView you can set background resource for layout containing by that cardview like following.

<android.support.v7.widget.CardView    xmlns:android="http://schemas.android.com/apk/res/android"   xmlns:card_view="http://schemas.android.com/apk/res-auto"   android:id="@+id/card_view"   android:layout_width="match_parent"   android:layout_height="wrap_content"   android:layout_margin="@dimen/activity_vertical_margin"   card_view:cardCornerRadius="12dp"   card_view:cardElevation="12dp">      <LinearLayout         android:id="@+id/myLayout"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:orientation="vertical">         <LinearLayout             android:layout_width="match_parent"             android:layout_height="wrap_content"             android:orientation="vertical">              .....     </LinearLayout>  </android.support.v7.widget.CardView> 

and

LinearLayout myLayout=(LinearLayout) findViewById(R.id.myLayout); myLayout.setBackgroundResource(R.drawable.card1); 

I hope this will help you.



回答2:

Use card_view:cardBackgroundColor="#FFFFFFFF" instead of android:background="#FFFFFFFF"
Programatically use, card.setCardBackgroundColor(color) instead of card.setBackgroundColor(color)



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!