1
2

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 3 years have passed since last update.

Fragmentから他のフラグメントへの画面遷移

Posted at

FragmentからFragmentへの遷移

画面遷移の動きは、以下のようになります。

画面収録-2021-01-21-10.13.11.gif

動きとしては、
・MainActivityにFragment01(WelcomeFragment)を表示
・Fragment01からFragment02(MainFragment)へ遷移
・Fragment02からFragment03(SubFragment)へ遷移


サンプルコード

WelcomeFragment
class WelcomeFragment: Fragment(R.layout.welcome_fragment) {

    private var _binding: WelcomeFragmentBinding? = null //
    private val binding: WelcomeFragmentBinding get() =  _binding!!

    override fun onViewCreated(view: View, saveInstanceState: Bundle?) {
        super.onViewCreated(view, saveInstanceState)
        this._binding = WelcomeFragmentBinding.bind(view)

        binding.next.setOnClickListener{
            findNavController().navigate(R.id.action_welcomeFragment_to_mainFragment)
        }
    }
}
MainFragment
class MainFragment:Fragment(R.layout.main_fragment) {

    private var _binding: MainFragmentBinding? = null //
    private val binding: MainFragmentBinding get() = _binding!!

    override fun onViewCreated(view: View, saveInstanceState: Bundle?) {
        super.onViewCreated(view, saveInstanceState)
        this._binding = MainFragmentBinding.bind(view)

        binding.nextTwo.setOnClickListener{
            findNavController().navigate(R.id.action_mainFragment_to_subFragment)
        }
    }
}
class SubFragment: Fragment(R.layout.sub_fragment) {
    private var _binding: SubFragmentBinding? = null
    private val binding: SubFragmentBinding get() = _binding!!

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        this._binding = SubFragmentBinding.bind(view)

        binding.nextLastButton.setOnClickListener {
            Toast.makeText(context,"よくできました",Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        this._binding = null
    }
}

View bindを使用しているため、以下をbulidに追加する

android {
  ...
  buildFeatures {
      viewBinding true
  }
}

/* または
android {
  ...
  viewBinding {
      enabled = true
  }
}
*/

追記:Fragmentにコンストラクタで、以下を渡してますが、推奨されていないようです。

R.layout~

Reference:

1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?