2018年4月11日水曜日

reified を使って lazy で intent から extra を取り出す部分を共通化する

lazy で intent から extra を取り出す部分を reified を使って Activity の拡張関数として定義してみました。
  1. inline fun <reified T> Activity.lazyWithExtras(key: String): Lazy<T> {  
  2.     return lazy { intent.extras.get(key) as T }  
  3. }  
  1. class ProfileActivity : AppCompatActivity() {  
  2.   
  3.     private val name: String by lazyWithExtras(EXTRAS_NAME)  
  4.     private val age: Int by lazyWithExtras(EXTRAS_AGE)  
  5.   
  6.     override fun onCreate(savedInstanceState: Bundle?) {  
  7.         super.onCreate(savedInstanceState)  
  8.         val textView = TextView(this)  
  9.         setContentView(textView)  
  10.   
  11.         textView.text = "$name $age"  
  12.     }  
  13.   
  14.     companion object {  
  15.         private const val EXTRAS_NAME = "name"  
  16.         private const val EXTRAS_AGE = "age"  
  17.   
  18.         fun createIntent(context: Context, name: String, age: Int): Intent {  
  19.             return Intent(context, ProfileActivity::class.java).apply {  
  20.                 putExtra(EXTRAS_NAME, name)  
  21.                 putExtra(EXTRAS_AGE, age)  
  22.             }  
  23.         }  
  24.     }  
  25. }  
Fragment では arguments は NonNull 前提としました
  1. inline fun <reified T> Fragment.lazyWithArgs(key: String): Lazy<T> {  
  2.     return lazy { arguments!!.get(key) as T }  
  3. }  
  1. class ProfileFragment : Fragment() {  
  2.   
  3.     private val name: String by lazyWithArgs(ARGS_NAME)  
  4.     private val age: Int by lazyWithArgs(ARGS_AGE)  
  5.   
  6.     override fun onActivityCreated(savedInstanceState: Bundle?) {  
  7.         super.onActivityCreated(savedInstanceState)  
  8.   
  9.         textView.text = "$name $age"  
  10.     }  
  11.   
  12.     companion object {  
  13.         private const val ARGS_NAME = "name"  
  14.         private const val ARGS_AGE = "age"  
  15.   
  16.         fun newInstance(name: String, age: Int): ProfileFragment {  
  17.             return ProfileFragment().apply {  
  18.                 arguments = Bundle().apply {  
  19.                     putString(ARGS_NAME, name)  
  20.                     putInt(ARGS_AGE, age)  
  21.                 }  
  22.             }  
  23.         }  
  24.     }  
  25. }  

0 件のコメント:

コメントを投稿