如何使自定义组件在Android强制?



我们和5个人一起做一个项目。我有自定义TextView组件在Android项目。我的一些团队朋友直接使用Android Textview(或AppCompatTextView)。我想强制使用我创建的文本视图作为自定义TextView。

我该怎么做?我期待你的帮助,谢谢。

而编码指南和代码审查应该抓住这些问题。你也可以创建一个自定义的lint检查,并强制你的构建在lint错误时失败。

像这样:

class TextViewDetector : ResourceXmlDetector() {
override fun getApplicableElements(): Collection<String>? {
return listOf(
"android.widget.TextView", "androidx.appcompat.widget.AppCompatTextView"
)
}
override fun visitElement(context: XmlContext, element: Element) {
context.report(
ISSUE, element, context.getLocation(element),
"Do not use TextView"
)
}
companion object {
val ISSUE: Issue = Issue.create(
"id",
"Do not use TextView",
"Use custom view",
CORRECTNESS, 6, Severity.ERROR,
Implementation(TextViewDetector::class.java, RESOURCE_FILE_SCOPE)
)
}
}

有一个指南,一个来自google的示例库和一个关于如何编写自定义lint检查的广泛api指南。

您可以创建自己的ViewInflater

class MyViewInflater { 
fun createView(
parent: View?, name: String?, context: Context,
attrs: AttributeSet, inheritContext: Boolean,
readAndroidTheme: Boolean, readAppTheme: Boolean, wrapContext: Boolean
): View {
// ...
val view: View = when (name) {
"TextView",
"androidx.appcompat.widget.AppCompatTextView",
"com.google.android.material.textview.MaterialTextView" -> createMyTextView(context, attrs)
//other views
}
//...

return view
}

fun createMyTextView(context: Context, attrs: AttributeSet) = MyTextView(context, attrs)
}

并安装到你的应用主题

<style name="Theme.MyAppTheme" parent="Theme.SomeAppCompatParentTheme">
<item name="viewInflaterClass">package.MyViewInflater</item>
</style>

它将返回你指定的所有标签的View

看到AppCompatViewInflater

没有技术方法可以做到这一点。答案是编码指南和代码审查。

最新更新