Android自定義View使用系統自有屬性

原文鏈接: Android自定義View使用系統自有屬性 - Stars-One的雜貨小窩

本篇默認各位有自定義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中寫的時候不會有對應屬性的代碼提示...

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章