Android:CardView 实现卡片式设计
一、一个简单的使用Demo
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.cardview.widget.CardView
android:id="@+id/card_view"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<TextView
android:id="@+id/content1"
android:text="内容"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
二、属性
1.背景颜色
布局中设置
app:cardBackgroundColor="@android:color/holo_blue_bright"
代码中设置
mCardView.setCardBackgroundColor(getResources().getColor(android.R.color.holo_blue_bright));
注意
(1)View自带原本的属性android:background="" 已经没有效果了,被下面的方法替代了
(2)下面提供的api只能设置颜色不能设置图片
2.设置圆角
布局中设置
app:cardCornerRadius="50dp"
代码中设置
mCardView.setRadius(20);
3.设置圆角
布局中设置
app:cardCornerRadius="50dp"
代码中设置
mCardView.setRadius(20);
4.设置阴影效果
布局中设置
app:cardElevation="30dp"
代码中设置
mCardView.setCardElevation(10);
5.设置最大阴影
布局中设置
app:cardMaxElevation="100dp"
代码中设置
mCardView.setMaxCardElevation(10);
6.设置内边距
布局中设置
app:contentPadding="10dp"
app:contentPaddingTop="10dp"
app:contentPaddingBottom="10dp"
app:contentPaddingLeft="10dp"
app:contentPaddingRight="10dp"
代码中设置
mCardView.setPadding(10,10,10,10);
7.自动设置内边距,让内容不会与圆角重叠
布局中设置
app:cardPreventCornerOverlap="true"
8.兼容模式
个别机型(说的就是你,喜欢瞎搞的华为)或者Android版本使用CardView没有效果,可能需要开启兼容模式
app:cardUseCompatPadding="true"
三、实践:实现一个圆形的CardView
因为,在onCreate生命周期里,CardView并没有测量绘制完成,所以我们需要等CardView运行完全部绘制工作后在执行设置圆角的代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCardView = findViewById(R.id.card_view);
mCardView.post(new Runnable() {
@Override
public void run() {
mCardView.setRadius(mCardView.getWidth()/2);
}
});
}