有一个单独的模块 AndroidLibary
在其中我创建一个自定义视图
我创建自定义属性并给它们默认值
<declare-styleable name="TestView">
<attr name="_name_TestView" format="string" />
<attr name="_info_TestView" format="string" />
</declare-styleable>
<style name="TestView">
<item name="_name_TestView">test</item>
<item name="_info_TestView">info</item>
</style>
在代码中获取属性
context.theme.obtainStyledAttributes(
attrs,
R.styleable.TestView,
0,
0
)
我将模块连接到项目,
我想更改项目 (而不是模块)的主题,以便默认属性_name_TestView
为customTest
. 怎么做?
查看代码
class TestView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : FrameLayout(context, attrs, R.attr.TestViewAtr) {
init {
inflate(context, R.layout.test_view, this)
}
private val xml =
context.theme.obtainStyledAttributes(
attrs,
R.styleable.TestView,
0,
0
)
val button by lazy { findViewById<Button>(R.id.testButton) }
val textView by lazy { findViewById<TextView>(R.id.textView) }
var text: String = xml.getStringOrThrow(R.styleable.TestView__name_TestView)
.apply { text = this }
set(value) {
field = value
button.setText(field)
}
var helpText: String = xml.getStringOrThrow(R.styleable.TestView__info_TestView)
.apply { helpText = this }
set(value) {
field = value
textView.text = field
}
private val closeXml = { xml.recycle() }.apply { this.invoke() }
}
在模块中我们创建了 3 个东西:
TestView
- 对于我们将使用的属性。该名称必须与自定义 View 类的名称匹配。然后我们将能够在设计模式中看到所有自定义参数。TestViewDefStyle
- 属性的默认样式TestViewStyle
- 样式链接,以便您可以从外部更改属性在我们的自定义视图 y 的类中
TypedArray
,我们指示我们创建的所有内容一切正常。您可以更改标记中每个元素的参数。标记中未指定的内容将从MODULE 的默认值中提取。
要更改APP的默认值,您应该
app:_name_TestView="wlad"
(否则你会像我一样受苦40分钟)CustomTestView
并继承模块的默认样式,TestViewDefStyle
这里我们覆盖必要的属性