Home > Blockchain >  How to make Custom Components mandatory in Android?
How to make Custom Components mandatory in Android?

Time:12-21

We are working with 5 people on a project. I have custom TextView component in Android project. Some of my team friends are using Android Textview (or AppCompatTextView) directly. I want to make it mandatory to use the text view that I created as a custom TextView.

How do I do this? I look forward to your help, thank you.

CodePudding user response:

While coding guidelines and code reviews should catch those issues. You could also create a custom lint check and force your builds to fail on lint errors.

Something like this:

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)
        )
    }
}

There is a guide, an example repository from google and an extensive api guide on how to write custom lint checks.

CodePudding user response:

You can create your own 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)
}

and install it in your app theme

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

It will return your View for all tags you have specified

See AppCompatViewInflater

CodePudding user response:

There's no technical way to do this. The answer is coding guidelines and code reviews.

  • Related