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

相关推荐
君的名字1 小时前
怎么判断一个Android APP使用了flutter 这个跨端框架
android·flutter
淡淡的香烟2 小时前
Android12 launcher3修改App图标白边问题
android
猿小蔡-Cool4 小时前
Kotlin中let、run、with、apply及also的差别
kotlin
橙子199110164 小时前
Kotlin 中该如何安全地处理可空类型?
开发语言·kotlin·log4j
limingade5 小时前
手机打电话时由对方DTMF响应切换多级IVR语音菜单(话术脚本与实战)
android·智能手机·语音识别·蓝牙电话·多级ivr导航·手机个人400电话·手机电话实现ivr语音导航
知北游天5 小时前
Linux:再谈进程地址空间
android·linux·运维
君的名字6 小时前
【跨端框架检测】使用adb logcat检测Android APP使用的跨端框架方法总结
android
qq_171538857 小时前
让MySQL更快:EXPLAIN语句详尽解析
android·数据库·mysql
每次的天空7 小时前
Android-Glide学习总结
android·学习·glide
“初生”15 小时前
安卓手机安装 ChatGPT 全流程图文指南
android·chatgpt·智能手机