Custom Lint Rule to Check All Views in Layouts - android

In the app I'm working on, it is imperative that all views in all layout files have an id set on them. So I'm trying to build a custom lint rule to enforce this.
Normally, one would use the getApplicableElements() method from XmlScanner and include a list of strings for each element tag. However, I can't seem to find a way to make this look at all elements in an XML layout which subclass View.
I tried using XmlScannerConstants.ALL, however, that looks at every single element in every single XML file. Given that we have several other types of XML-based resources, that's not going to work.
My code for the inspector class is below. Does anyone know of a good way filter getApplicableElements() so it looks at every element that subclasses View, and nothing else?
class IdDetector : ResourceXmlDetector() {
companion object {
private const val ISSUE_ID = "MissingId"
private const val ISSUE_DESCRIPTION = "Missing required attribute 'id'"
private const val ISSUE_EXPLANATION = "Identifiers are required on all views."
val ISSUE = Issue.create(
id = ISSUE_ID,
briefDescription = ISSUE_DESCRIPTION,
explanation = ISSUE_EXPLANATION,
category = Category.A11Y,
priority = 10,
severity = Severity.FATAL,
androidSpecific = true,
implementation = Implementation(IdDetector::class.java, Scope.RESOURCE_FILE_SCOPE)
)
}
override fun getApplicableElements(): Collection<String>? = XmlScannerConstants.ALL
override fun visitElement(context: XmlContext, element: Element) {
if (!element.hasAttributeNS("http://schemas.android.com/apk/res/android", "id")) {
context.report(ISSUE, element, context.getLocation(element), ISSUE_DESCRIPTION)
}
}
}

There's the appliesTo(#NonNull ResourceFolderType folderType) method that can help you achieve that. In your case, I believe you will be only interested in targeting the layout folder. You're new detector would look something like this:
class IdDetector : ResourceXmlDetector() {
companion object {
private const val ISSUE_ID = "MissingId"
private const val ISSUE_DESCRIPTION = "Missing required attribute 'id'"
private const val ISSUE_EXPLANATION = "Identifiers are required on all views."
val ISSUE = Issue.create(
id = ISSUE_ID,
briefDescription = ISSUE_DESCRIPTION,
explanation = ISSUE_EXPLANATION,
category = Category.A11Y,
priority = 10,
severity = Severity.FATAL,
androidSpecific = true,
implementation = Implementation(IdDetector::class.java, Scope.RESOURCE_FILE_SCOPE)
)
}
override fun appliesTo(folderType: ResourceFolderType): Boolean = ResourceFolderType.LAYOUT == folderType
override fun getApplicableElements(): Collection<String>? = XmlScannerConstants.ALL
override fun visitElement(context: XmlContext, element: Element) {
if (!element.hasAttributeNS("http://schemas.android.com/apk/res/android", "id")) {
context.report(ISSUE, element, context.getLocation(element), ISSUE_DESCRIPTION)
}
}
}

Related

Android: Lottie Animation with dynamic text and custom font issue

I'm trying to dynamically swap a text inside a LottieAnimation in jetpack compose.
The lottie file is exported without glyphs
It's working when using the old android view inside a
AndroidView(factory = { context ->
val view = LottieAnimationView(context).apply {
setAnimation(R.raw.testing_no_glyphs)
playAnimation()
repeatCount = LottieConstants.IterateForever
}
val textDel = object : TextDelegate(view) {
override fun getText(layerName: String?, input: String?): String {
return when (layerName) {
"Test234" -> "OtherLettersHere"
else -> super.getText(layerName, input)
}
}
}
val fontDel = object : FontAssetDelegate() {
override fun getFontPath(fontFamily: String?, fontStyle: String?, fontName: String?): String {
return "fonts/[MyFontInside /assets].ttf"
}
}
view.setTextDelegate(textDel)
view.setFontAssetDelegate(fontDel)
return#AndroidView view
})
But I can't find the correct handles in the JetpackCompose version of Lottie to get the same result.
If we export the lottie with glyphs, it's works for the letters in the chars array inside the lottie json. But we want to be able to replace with any letters/symbols, so this isn't a viable solution.
I've noticed in the 5.3.0-SNAPSHOT that a fontMap parameter has been added, but I can't figure out which key to hit with it.
Here is my code:
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(LottieProperty.TEXT, value = "AaBbCcEeFf", keyPath = arrayOf("Test234"))
)
val composition by rememberLottieComposition(
spec = LottieCompositionSpec.RawRes(R.raw.testing)
)
val progress by animateLottieCompositionAsState(composition, iterations = LottieConstants.IterateForever)
LottieAnimation(
composition,
{ progress },
dynamicProperties = dynamicProperties,
fontMap = mapOf("fName" to Typeface.createFromAsset(LocalContext.current.assets, "fonts/[MyFontInside /assets].ttf"))
)
It just shows a blank for all the texts inside the Lottie Animation - so this is kinda where i'm stuck.
After some trial an error I found a way to add the typeface for a specific layer:
val typeface = Typeface.createFromAsset(LocalContext.current.assets, "fonts/[MyFontInside /assets].ttf")
val dynamicProperties = rememberLottieDynamicProperties(
rememberLottieDynamicProperty(LottieProperty.TEXT, value = "AaBbCcEeFf", keyPath = arrayOf("Test234")),
--> rememberLottieDynamicProperty(LottieProperty.TYPEFACE, value = typeface, keyPath = arrayOf("Test234")),
)
Hence there is no need for the fontMap in my case

Button onClick keep replacing values in mutableStateList

I'm trying to display a 4x4 grid with values that change depending on user input. To achieve that, I created mutableStateListOf that I use in a ViewModel to survive configuration changes. However, when I try to replace a value in that particular list using button onClick, it keeps doing that until app crashes. I can't understand why is onReplaceGridContent looping after clicking the button once. Currently, my code looks like this:
ViewModel:
class GameViewModel : ViewModel(){
var gameGridContent = mutableStateListOf<Int>()
private set // Restrict writes to this state object to private setter only inside view model
fun replaceGridContent(int: Int, index: Int){
gameGridContent[index] = int
}
fun removeGridContent(index: Int){
gameGridContent[index] = -1
}
fun initialize(){
for(i in 0..15){
gameGridContent.add(-1)
}
val firstEmptyGridTile = GameUtils.getRandomTilePosition(gameGridContent)
val firstGridNumber = GameUtils.getRandomTileNumber()
gameGridContent[firstEmptyGridTile] = firstGridNumber
}
}
Button:
Button(
onClick = {
onReplaceGridContent(GameUtils.getRandomTileNumber(),GameUtils.getRandomTilePosition(gameGridContent))},
colors = Color.DarkGray
){
Text(text = "Add number to tile")
}
Activity Composable:
#Composable
fun gameScreen(gameViewModel: GameViewModel){
gameViewModel.initialize()
MainStage(
gameGridContent = gameViewModel.gameGridContent,
onReplaceGridContent = gameViewModel::replaceGridContent,
onRemoveGridContent = gameViewModel::removeGridContent
)
}
Your initialize will actually run on every recomposition of gameScreen:
You click on a tile - state changes causing recomposition.
initializa is called and changes the state again causing recomposition.
Step 2 happens again and again.
You should initialize your view model in its constructor instead (or use boolean flag to force one tim initialization) to make it inly once.
Simply change it to constructor:
class GameViewModel : ViewModel(){
var gameGridContent = mutableStateListOf<Int>()
private set // Restrict writes to this state object to private setter only inside view model
fun replaceGridContent(int: Int, index: Int){
gameGridContent[index] = int
}
fun removeGridContent(index: Int){
gameGridContent[index] = -1
}
init {
for(i in 0..15){
gameGridContent.add(-1)
}
val firstEmptyGridTile = GameUtils.getRandomTilePosition(gameGridContent)
val firstGridNumber = GameUtils.getRandomTileNumber()
gameGridContent[firstEmptyGridTile] = firstGridNumber
}
}
Now you don't need to call initialize in the composable:
#Composable
fun gameScreen(gameViewModel: GameViewModel){
MainStage(
gameGridContent = gameViewModel.gameGridContent,
onReplaceGridContent = gameViewModel::replaceGridContent,
onRemoveGridContent = gameViewModel::removeGridContent
)
}

When using List as State, how to update UI when item`attribute change in Jetpack Compose?

For example, I load data into a List, it`s wrapped by MutableStateFlow, and I collect these as State in UI Component.
The trouble is, when I change an item in the MutableStateFlow<List>, such as modifying attribute, but don`t add or delete, the UI will not change.
So how can I change the UI when I modify an item of the MutableStateFlow?
These are codes:
ViewModel:
data class TestBean(val id: Int, var name: String)
class VM: ViewModel() {
val testList = MutableStateFlow<List<TestBean>>(emptyList())
fun createTestData() {
val result = mutableListOf<TestBean>()
(0 .. 10).forEach {
result.add(TestBean(it, it.toString()))
}
testList.value = result
}
fun changeTestData(index: Int) {
// first way to change data
testList.value[index].name = System.currentTimeMillis().toString()
// second way to change data
val p = testList.value[index]
p.name = System.currentTimeMillis().toString()
val tmplist = testList.value.toMutableList()
tmplist[index].name = p.name
testList.update { tmplist }
}
}
UI:
setContent {
LaunchedEffect(key1 = Unit) {
vm.createTestData()
}
Column {
vm.testList.collectAsState().value.forEachIndexed { index, it ->
Text(text = it.name, modifier = Modifier.padding(16.dp).clickable {
vm.changeTestData(index)
Log.d("TAG", "click: ${index}")
})
}
}
}
Both Flow and Compose mutable state cannot track changes made inside of containing objects.
But you can replace an object with an updated object. data class is a nice tool to be used, which will provide you all copy out of the box, but you should emit using var and only use val for your fields to avoid mistakes.
Check out Why is immutability important in functional programming?
testList.value[index] = testList.value[index].copy(name = System.currentTimeMillis().toString())

How to set the value of property in Kotlin

I have tried to set a property value as in the following snippet.This SO question is not answering the question.
var person = Person("john", 24)
//sample_text.text = person.getName() + person.getAge()
var kon = person.someProperty
person.someProperty = "crap" //this doesn't allow me to set value
kon = "manulilated" //this allows me to set the value
sample_text.text = kon
class Person(val n: String, val a: Int){
var pname: String = n
var page: Int = a
var someProperty: String = "defaultValue"
get() = field.capitalize()
private set(value){field = value}
fun Init(nm: String, ag: Int){
pname = nm
page = ag
}
fun getAge(): Int{
return page
}
fun getName(): String{
return pname
}
}
Why was I able to set the value of the Person class on the second line but not the first line?
First, the private modifier is your problem.
Change
private set(value){field = value}
To
set(value){field = value}
//public by default
Otherwise you can’t use the setter outside the class. Read here.
For members declared inside a class:
private means visible inside this class only (including all its members);
Second, you’re misunderstanding something:
var kon = person.someProperty
kon = "manulilated"
In these lines you’re not changing the property in the object. After creating the variable kon, being a String pointing to someProperty, you reassign that local variable to something else. This reassignment is unequal to changing the value of person.someProperty! It has totally no effect in the object.
someProperty has a private setter. You can't set it outside the class when the setter is private
This is a good example of trying to write Kotlin in Java style.
Here is how this would like in Kotlin facilitating the language capabilities. One can see how much shorter and clearer the code is. The Person class has only 3 lines.
Using data class spares us from defining hash and equals and toString.
fun test() {
val person = Person("john", 24)
var kon = person.someProperty
person.someProperty = "crap" //this doesn't allow me to set value
kon = "manulilated" //this allows me to set the value (yeah, but not in the class, this is a local string)
val sample_text = SampleText("${person.name}${person.age}")
sample_text.text = kon
println("Person = $person")
println("Kon = $kon")
println("Sample Text = $sample_text")
}
/** class for person with immutable name and age
* The original code only has a getter which allows to use 'val'.
* This can be set in the constructor, so no need for init code. */
data class Person(val name: String, val age: Int) {
/** The field value is converted to uppercase() (capitalize is deprecated)
* when the value comes in, so the get operation is much faster which is
* assumed to happen more often. */
var someProperty: String = "defaultValue"
// setter not private as called from outside class
set(value) { field = value.uppercase() }
}
/** simple class storing a mutable text for whatever reason
* #param text mutable text
*/
data class SampleText(var text: String) {
override fun toString(): String {
return text
}
}
This is the result:
Person = Person(name=john, age=24)
Kon = manulilated
Sample Text = manulilated

How to use selectableButtonBackground on Anko?

How do I use selectableButtonBackground attribute on a custom View that uses Anko's apply() method inside its constructor like the following structure?
class XPTO(context: Context) : CardView(context) {
init {
this.apply {
// I'd like to invoke selectableButtonBackground here
}
}
I've tried to do context.obtainStyledAttributes(arrayOf(R.attr.selectableItemBackground).toIntArray()).getDrawable(0) but with no success.
I just created an extension function to get the resource ids for attributes.
val Context.selectableItemBackgroundResource: Int get() {
return getResourceIdAttribute(R.attr.selectableItemBackground)
}
fun Context.getResourceIdAttribute(#AttrRes attribute: Int) : Int {
val typedValue = TypedValue()
theme.resolveAttribute(attribute, typedValue, true)
return typedValue.resourceId
}
This way you can also add more attributes if needed. Example to put it in anko:
frameLayout {
textView {
text = "Test"
backgroundResource = selectableItemBackgroundResource
isClickable = true
}
}
Don't forget the isClickable, else you won't see anything when you're clicking the textView
Another way to achieve this with Anko:
val backgroundResource = attr(R.attr.selectableItemBackgroundBorderless).resourceId

Categories

Resources