侧边栏壁纸
博主头像
Stars-One的杂货小窝博主等级

所有的创作都是有价值的

  • 累计撰写 257 篇文章
  • 累计创建 46 个标签
  • 累计收到 27 条评论

目 录CONTENT

文章目录

Android自定义View使用系统自有属性

Stars-one
2023-11-12 / 0 评论 / 0 点赞 / 99 阅读 / 3007 字

本篇默认各位有自定义View的相关知识,本篇只作为一个小知识点补充

有这样一种情况,比如说我们的一个自定义View中有个maxLines的属性,但是我们会注意到这个maxLines其实Android里面已经存在了(如TextView中),我们能否直接去复用此属性呢?

实现的效果实际就是把代码里我们之前的属性引用写的app:maxLInes改为了android:maxLines

答案是可以的,那么应该如何操作呢?,如下代码

class FlowLayout : ViewGroup {


    constructor(context: Context, attr: AttributeSet) : super(context, attr) {
        //注意这里这里的obtainStyledAttributes的第二个参数,数一个int数组(需要有个属性数值,且数组长度为1)
        //如果要想使用多个,就像下面那样再写一次
        context.obtainStyledAttributes(attr, intArrayOf(android.R.attr.maxLines)).apply {
            //取值类型得看对应属性定义的类型
            val maxLine = getInt(0, Int.MAX_VALUE)
            Log.d("starsone", "maxLine: $maxLine ")
            recycle()
        }

        context.obtainStyledAttributes(attr, intArrayOf(android.R.attr.maxRows)).apply {
            //这里
            val maxRow = getInt(0, Int.MAX_VALUE)
            Log.d("starsone", "maxRow: $maxRow ")
            recycle()
        }
    }

之后在xml中使用 (这里注意是android前缀而不是app前缀):

<com.example.myapplication.view.FlowLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/flowlayout"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
+    android:maxLines="10"
+    android:maxRows="11"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FlowLayoutTestActivity">
    
/>

PS: 不过这个方法有个缺陷,就是在xml中写的时候不会有对应属性的代码提示…

参考

0

评论区