因?yàn)樽远xView 有正向和反向兩個(gè)狀態(tài),所以需要在初始化時(shí)區(qū)分加載哪個(gè)layout
在Android中,要在自定義View中增加屬性,你需要完成以下步驟:
-
在res/values/attrs.xml文件中定義屬性。
-
在自定義View的構(gòu)造函數(shù)中獲取這些屬性。
-
在布局文件中使用這些屬性。
attrs.xml:文章來源:http://www.zghlxwxcb.cn/news/detail-857731.html
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SeriseViewState">
<attr name="overturn" format="string" />
</declare-styleable>
</resources>
自定義VIEW 中獲取屬性文章來源地址http://www.zghlxwxcb.cn/news/detail-857731.html
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
// 正向view
var layout = R.layout.item_aaa
if (attrs != null) {
val a: TypedArray = context.obtainStyledAttributes(attrs,R.styleable.SeriseViewState)
val text = a?.getString(R.styleable.SeriseViewState_overturn)
if (!TextUtils.isEmpty(text) && text.equals("1")) {
// 設(shè)置反向
layout = R.layout.item_bbb
}
}
val view: View = LayoutInflater.from(context).inflate(layout, this)
}
到了這里,關(guān)于Android 自定義view 中增加屬性,初始化時(shí)讀取的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!