随笔 - 632  文章 - 17  评论 - 54  阅读 - 93万

Android可设置任意高度的TextView,如:设置0.5px设置0.1px等等

一、概述

  今天UI给提了一个bug,说分割线的宽度有问题。必须要求线的高度为0.5px。但是layout_height只允许输入整数。想通过直接设置View高度的办法宣告凉凉的。

  然后突然想到Android绘图工具上可以把线的宽度设置成任意的。哎,还别说,这个办法还真行

二、原理

  自定义一View,然后重写其onDraw方法,用canvas把相关的线线绘制出来。绘制出来的线可以是任意高度的,所以这种方案一下就满足了需求。下面看看具体代码怎样干(Kotlin写的)。如果是用Java的小伙伴,自行转换为Java代码。

三、代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class ZeroDianFiveTextView : androidx.appcompat.widget.AppCompatTextView {
 
    private var lineHeight: Float = 0.25f
    private var lineColor: Int = resources.getColor(R.color.color_333333)
 
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        val array = context.obtainStyledAttributes(attrs, R.styleable.ZeroDianFive)
        lineHeight = array.getFloat(R.styleable.ZeroDianFive_zeroLineHeight, 0.25f)
        lineColor = array.getColor(
            R.styleable.ZeroDianFive_zeroLineColor,
            resources.getColor(R.color.color_333333)
        )
    }
 
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        val paint = Paint()
        paint.isAntiAlias = true;
        paint.strokeWidth = PxUtils.dp2px(context, lineHeight).toFloat()
        paint.color = lineColor
        canvas?.drawLine(0f, 0f, this.width.toFloat(), 0f, paint)
 
    }
}

  

1
2
3
4
5
6
<com.uns.uu.view.ZeroDianFiveTextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:zeroLineColor="@color/B6B6B8"
    app:zeroLineHeight="0.3"
     />

  好了搞定了

posted on   飘杨......  阅读(708)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
历史上的今天:
2014-10-13 android 通讯类资料整理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示