Android改造CardView为圆形View,Kotlin

Android改造CardView为圆形View,Kotlin

可以利用androidx.cardview.widget.CardView的cardCornerRadius特性,将CardView改造成一个圆形的View,技术实现的关键首先设定CardView为一个宽高相等的View(正方形),然后将radius特意设置成宽度(或高度,一样,因为正方形,宽高相等)的1/2,此时CardView自然就变成一个圆。

(1)kotlin代码运行时生成:

Kotlin 复制代码
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val circularCardView = CircularCardView(this)
        circularCardView.setCardBackgroundColor(Color.BLUE)
        setContentView(circularCardView)
    }
}

class CircularCardView(ctx: Context) : CardView(ctx) {
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = measuredWidth
        setMeasuredDimension(width, width)
        radius = (width / 2).toFloat()
    }
}

(2)在xml布局中实现:

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="200dp"
        android:layout_height="200dp"
        app:cardBackgroundColor="@android:color/holo_orange_light"
        app:cardCornerRadius="100dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>

Android RoundedBitmapDrawable:Android官方的圆角图形图象实现方案_android 官方圆角-CSDN博客Android RoundedBitmapDrawable:Android官方的圆角图形图象实现方案RoundedBitmapDrawable是Android在support v4的扩展包中新增的实现圆角图形的关键类,借助RoundedBitmapDrawable的帮助,可以轻松的以Android标准方式实现圆角图形图象。写一个简单的例子。写一个线性布局,竖直方向放三个Im_android 官方圆角https://blog.csdn.net/zhangphil/article/details/51829650Android CardView设置成普通的Framelayout-CSDN博客比如可以这样写代码,CardView就变成普通的FrameLayout:https://blog.csdn.net/zhangphil/article/details/52911922

相关推荐
小袁拒绝摆烂40 分钟前
SQL开窗函数
android·sql·性能优化
apihz1 小时前
VM虚拟机全版本网盘+免费本地网络穿透端口映射实时同步动态家庭IP教程
android·服务器·开发语言·网络·数据库·网络协议·tcp/ip
baidu_247438612 小时前
Android MPAndroidChart使用
android
天平3 小时前
react native现代化组件库的推荐 【持续更新...】
android·前端·react native
apihz3 小时前
通用图片搜索-搜狗源免费API接口使用指南
android·java·python·php·音视频
你过来啊你4 小时前
Android开发中ARouter使用和原理详解
android
apihz5 小时前
腾讯云轻量服务器创建快照免费API接口教程
android·服务器·数据库·python·网络协议·tcp/ip·腾讯云
Kiri霧6 小时前
Noting
android·开发语言·kotlin
东风西巷12 小时前
NealFun安卓版:创意无限,娱乐至上
android·人工智能·智能手机·娱乐·软件需求
小李飞飞砖17 小时前
Sophix、Tinker 和 Robust 三大主流 Android 热修复框架的详细对比
android