15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Kotlin】Bundleを使ったFragment間の値渡し

Last updated at Posted at 2018-12-20

今回はFragmentPagerAdapterのgetItemメソッドの中で、position(Int)の値渡しをしてみます。

渡す側

HogeFragment.kt

override fun getItem(position: Int): Fragment? {
    // Bundle(オブジェクトの入れ物)のインスタンスを作成する
    val bundle = Bundle()
    // Key/Pairの形で値をセットする
    bundle.putInt("KEY_POSITION", position)
    // Fragmentに値をセットする
    val fragment = FugaFragment()
    fragment.setArguments(bundle)

    return fragment
}

渡したい値の型に応じてputStringputBooleanなどが使えます。

受け取る側

FugaFragment.kt

// 値がセットされなかった時のために初期値をセットしておく
private var position = 0

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState){
    // Bundleを取得する
    val bundle = arguments
    // Bundleがセットされていたら値を受け取る
    if (bundle != null) {
        position = bundle.getInt("KEY_POSITION")
    }
}

受け取りたい値の型に応じてgetStringgetBooleanなどが使えます。

15
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?