[Android] Released View-SavedState-ktx, an easy-to-use library for SavedState

Takumi WADA
View-SavedState-ktx
2 min readMay 11, 2020
View-SavedState-ktx 1.0.0

# What is View-SavedState-ktx

A library that makes it easy to handle AndroidX SavedState with Delegated Properties. It is easy to describe in Activity and Fragment.

## What is AndroidX SavedState

It is one of the AndroidX libraries and is a library that can be hooked to the savedInstanceState’s state saving / restoring process.

# What is nice about View-SavedState-ktx

## onSavedInstanceState() is no longer needed

The state variables of an Activity or Fragment that previously had to be saved with onSavedInstanceState() and restored with onCreate can be written in Kotlin’s Delegated Properties as:

class SampleActivity : AppCompatActivity(R.layout.sample_activity) {
private val state by savedState()
private var count by state.property(
{ getInt(it) }, { key, value -> putInt(key, value) }
)
private var text by state.property(
{ getString(it, "default value") },
{ key, value -> putString(key, value) }
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// You can use properties after onCreate
count++
}
}

State saving / restoring is done automatically, so you don’t need to call onSavedInstanceState() and you don’t need key constants for state saving / restoring.

## A value of Activity Intent or Fragment Arguments is the default value

When you receive the initial value of the state in Intent or Arguments, it becomes the default value and can be handled transparently.

class SampleActivity : AppCompatActivity(R.layout.sample_activity) {
private val state by savedState()
private var count by state.property(
{ getInt(it) }, { key, value -> putInt(key, value) }
)
private var text by state.property(
{ getString(it, "default value") },
{ key, value -> putString(key, value) }
)
companion object {
fun createIntent(context: Context, count: Int) =
Intent(context, SampleActivity::class.java)
.also {
it.putExtra(SampleActivity::count.name, count)
}
}
}

Variable names can be used as keys in the property reference, eliminating the need to define key constants.

# How to use View-SavedState-ktx

Add the following to build.gradle.

repositories {
maven { url "https://www.jitpack.io" }
}
dependencies {
implementation 'com.github.wada811:View-SavedState-ktx:1.0.0'
}

--

--