lazy で intent から extra を取り出す部分を reified を使って Activity の拡張関数として定義してみました。
inline fun <reified T> Activity.lazyWithExtras(key: String): Lazy<T> {
return lazy { intent.extras.get(key) as T }
}
class ProfileActivity : AppCompatActivity() {
private val name: String by lazyWithExtras(EXTRAS_NAME)
private val age: Int by lazyWithExtras(EXTRAS_AGE)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val textView = TextView(this)
setContentView(textView)
textView.text = "$name $age"
}
companion object {
private const val EXTRAS_NAME = "name"
private const val EXTRAS_AGE = "age"
fun createIntent(context: Context, name: String, age: Int): Intent {
return Intent(context, ProfileActivity::class.java).apply {
putExtra(EXTRAS_NAME, name)
putExtra(EXTRAS_AGE, age)
}
}
}
}
Fragment では arguments は NonNull 前提としました
inline fun <reified T> Fragment.lazyWithArgs(key: String): Lazy<T> {
return lazy { arguments!!.get(key) as T }
}
class ProfileFragment : Fragment() {
private val name: String by lazyWithArgs(ARGS_NAME)
private val age: Int by lazyWithArgs(ARGS_AGE)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
textView.text = "$name $age"
}
companion object {
private const val ARGS_NAME = "name"
private const val ARGS_AGE = "age"
fun newInstance(name: String, age: Int): ProfileFragment {
return ProfileFragment().apply {
arguments = Bundle().apply {
putString(ARGS_NAME, name)
putInt(ARGS_AGE, age)
}
}
}
}
}
0 件のコメント:
コメントを投稿