Binding Views without consideration of default states in android sdk

 

Photo by Randy Laybourne on Unsplash

I’m a freelance mobile developer specialized in Android native development.

With most projects I realized that there’s a pattern of common mistakes made in Android development. Some might be copied from Stack Overflow, some might arise from common sense and poor documentation.

Here I want to point out some of these mistakes and provide simple pointers on how to resolve these without the need for a big refactoring of the whole code base.

Imagine any MV* pattern you like. Eventually you’ll inflate a view hierarchy to display a default state of the screen you’re currently displaying. It’s just a simple profile information with name, age and an indicator stating that the user is a minor. So you’ll just set the visibility of that indicator to be visible if the user is a minor:

if (user.isMinor) minorIndicator.visibility = VISIBLE

Now it’s possible to refresh the screen manually, so that the data updates after it was changed somewhere else. Since it is the user’s birthday to adulthood now, the minor indicator should not be displayed anymore, but because of the fact, that it’s assumed to be gone by default it’s only changed to the visible state. So instead make sure to always set the state, regardless of the default:

minorIndicator.isVisible = user.isMinor

This also applies to text or any other data changing the default values of an inflated screen.

Always bind the data provided and don’t make assumptions about the actual state of the views

But if you need to set the visibility and the text at the same time, or any other combination of data, you could be clever about it and don’t waste resources providing a text of an invisible view. A common practice would be to provide an extension function to set the text and visibility at once:

fun TextView.setTextOrHide(text: CharSequence?) {
isVisible = if (text.isNullOrBlank()) false else {
this.text = text
true
}
}

Keeping this in mind will reduce the time you spend hunting for bugs related to your screen. Especially those found by end users and described from their non-technical perspective.


https://www.codeblogs.info/programming-stuff-on-codeblogs

https://www.codeblogs.info/hashmap-introduction

https://www.codeblogs.info/java-issues-fixed-in-kotlin

https://www.codeblogs.info/android-studio-stuck-at-installing-apk

https://www.codeblogs.info/make-link-clickable-in-container-that

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.