Android Development
LiveData is convenient, powerful and super easy to use. But, there are still some quirks that could possibly leads to some heads banging against walls.
How many times can I observe? In theory, we can observe livedata with multiple observers, just like the good old pub-sub pattern, right? Well, let’s test this out.
Let’s create a super simple livedata.
class MainViewModel : ViewModel() { private val _data = MutableLiveData<Int>() val data: LiveData<Int> = _data fun update(count: Int) { _data.
Let’s understand more about Android view’s measure and layout process, and have some fun along the way.
Let’s say we have this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.example.stubornview.StubbornView android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/design_default_color_primary" /> </LinearLayout> class StubbornView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { /** * 1. Parent LinearLayout combines developer's requirements * and the available space of itself into MeasureSpecs and * pass them here.
Yes, there is documentation and tons of sample apps out there. But they are all in a top down approach, meaning they give you the final result of how to use it first, and never tells you why and what is behind the scenes.
I will fix that in this article, and present a bottom up approach which leads to much better and deeper understanding.
First, at the bottom of things, we need to define what is ViewModel.
It is quite common in Android that we need some expandable widget to show and hide information. This is my first attempt, note that this is only a “sketch”, and I intentionally leave some room for improvement.
One interesting detail worth mentioning is how the animation is done. I used the reverse() function to play animation backwards in order to achieve a smooth and continuous feel.
Here is the code:
I was bored at night so decided to peek into the guts of how Android’s View Binding works. To my suprise the generated code is extremely simple.
Imagine you have a list_item.xml file and it looks like this:
<LinearLayout> <ImageView android:id="@+id/icon" /> <TextView android:id="@+id/name" /> </LinearLayout> Then the generated class will be like this:
public final class ListItemBinding implements ViewBinding { private final LinearLayout rootView; public final ImageView icon; public final TextView name; // Notice: private constructor private ListItemBinding(LinearLayout rootView, ImageView icon, TextView name) { this.