Created
August 5, 2022 02:25
-
-
Save tateisu/b62736becef4194a032ccb1b4e2483e1 to your computer and use it in GitHub Desktop.
Bundle.getParcelableCompat と View.onRestoreInstanceState の組み合わせを試す
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package jp.juggler.testparcelablecompat | |
import android.content.Context | |
import android.os.Build | |
import android.os.Bundle | |
import android.os.Parcelable | |
import android.util.Log | |
import android.view.View | |
import android.view.ViewGroup | |
import androidx.appcompat.app.AppCompatActivity | |
import jp.juggler.testparcelablecompat.BundleExt.getParcelableCompat | |
private const val TAG = "TestParcelableCompat" | |
class MainActivity : AppCompatActivity() { | |
override fun onCreate(savedInstanceState: Bundle?) { | |
Log.i(TAG, "MainActivity.onCreate savedInstanceState=$savedInstanceState") | |
super.onCreate(savedInstanceState) | |
val testView = TestView(this).apply { | |
id = R.id.testView | |
layoutParams = ViewGroup.LayoutParams( | |
ViewGroup.LayoutParams.MATCH_PARENT, | |
ViewGroup.LayoutParams.MATCH_PARENT, | |
) | |
} | |
setContentView(testView) | |
} | |
} | |
class TestView(context: Context) : View(context) { | |
companion object { | |
private const val STATE_SAVE_COUNT = "saveCount" | |
private const val STATE_SUPER = "TestView.super" | |
} | |
private var saveCount = 0 | |
override fun onSaveInstanceState(): Parcelable = | |
Bundle().apply { | |
val superState = super.onSaveInstanceState() | |
putParcelable(STATE_SUPER, superState) | |
putInt(STATE_SAVE_COUNT, ++saveCount) | |
Log.i(TAG, "TestView.onSaveInstanceState saveCount=$saveCount, superState=$superState") | |
} | |
override fun onRestoreInstanceState(state: Parcelable?) { | |
Log.i(TAG, "TestView.onRestoreInstanceState state=$state") | |
if (state is Bundle && state.containsKey(STATE_SUPER)) { | |
val superState = state.getParcelableCompat<Parcelable>(STATE_SUPER) | |
super.onRestoreInstanceState(superState) | |
saveCount = state.getInt(STATE_SAVE_COUNT) | |
Log.i( | |
TAG, | |
"TestView.onRestoreInstanceState saveCount=$saveCount, superState=$superState" | |
) | |
} else { | |
super.onRestoreInstanceState(state) | |
} | |
} | |
} | |
object BundleExt { | |
/** | |
* API 33 で Bundle.getParcelable(1引数)が deprecatedになった | |
* - 33 のソースを見ないとコレで動くのか分からん… | |
*/ | |
@Suppress("DEPRECATION") | |
inline fun <reified T : Any> Bundle.getParcelableCompat(key: String) = | |
if (Build.VERSION.SDK_INT >= 33) { | |
getParcelable(key, T::class.java) | |
} else { | |
getParcelable(key) as? T | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment