Home > Enterprise >  how to switch after clicking on the button in the menu to a fragment in which data binding is used
how to switch after clicking on the button in the menu to a fragment in which data binding is used

Time:04-18

enter image description here

enter image description here

class MainActivity : AppCompatActivity() { lateinit var binding : ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) }

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.bottom_nav_bar_main , menu)
    return true
}

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val intent : Intent
    when(item.itemId) {
        R.id.itemCourses -> {
            val fragment = CoursesFragment.newInstance()
        }
    }
    return true
}

}

class CoursesFragment : Fragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val binding = FragmentCoursesBinding.inflate(inflater , container , false)
    return binding.root
}

}

CodePudding user response:

Step 1 : Add FragmentContainerView to your activity xml

<androidx.fragment.app.FragmentContainerView
     android:id="@ id/container"
     android:layout_width="match_parent"
     android:layout_height="match_parent" />

Step 2 : In your MainActivity.class file, declare FragmentManager

private FragmentManager manager;

Step 3 : Initialize FragmentManager in onCreate()

manager = getSupportFragmentManager();

Step 4 : In your onOptionsItemSelected begin this fragment

Bundle bundle = new Bundle();
manager.beginTransaction()
                .replace(R.id.container, YourFragment.class, bundle, "TAG")
                .setReorderingAllowed(true)
                //.setCustomAnimations(R.anim.anim_enter, R.anim.anim_exit)
                .addToBackStack("TAG")
                .commit();
  • Related