How to create custom navigation drawer with bottom navigation view in android? - android

this is MainActivity
class MainActivity : AppCompatActivity(), FragmentDrawerListener,
BottomNavigationView.OnNavigationItemSelectedListener {
private lateinit var drawerFragment: DrawerFragment
#Inject
lateinit var mainActivityViewModel: MainActivityViewModel
#Inject
lateinit var appPreference: AppPreference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AndroidInjection.inject(this)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
navigation.setOnNavigationItemSelectedListener(this)
displayView()
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onDrawerItemSelected(view: View, position: Int) {
displayView(position)
}
private fun displayView() {
drawerFragment =
supportFragmentManager.findFragmentById(R.id.fragment_navigation_drawer) as DrawerFragment
drawerFragment.init(R.id.fragment_navigation_drawer, drawer_layout, toolbar)
displayView(0)
}
private fun displayView(position: Int) {
when (position) {
0 -> {
HomeFragment()
}
5 -> {
val intent = Intent(this, MerchantOnBoardingActivity::class.java)
startActivity(intent)
}
9 -> {
val intent = Intent(this, AppSecurityActivity::class.java)
startActivity(intent)
}
else -> {
val bundle = Bundle()
bundle.putInt("menuItemPosition", position - 1)
val intent = Intent(this, MenuActivity::class.java)
intent.putExtras(bundle)
startActivity(intent)
}
}
}
private fun showDefaultPage() {
val fragment = HomeFragment()
title = "Home"
val fragmentManager = supportFragmentManager
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.replace(R.id.main_content, fragment)
fragmentTransaction.commit()
supportActionBar?.title = title
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
var fragment: Fragment? = null
when (item.itemId) {
R.id.navigation_home -> fragment = HomeFragment()
R.id.navigation_monitor -> Toast.makeText(this, "Monitor", Toast.LENGTH_LONG).show()
R.id.navigation_profile -> Toast.makeText(this, "Profile", Toast.LENGTH_LONG).show()
}
return loadFragment(fragment)
}
private fun loadFragment(fragment: Fragment?): Boolean {
//switching fragment
if (fragment != null) {
supportFragmentManager
.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit()
return true
}
return false
}
}
This is my xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:local="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white"
android:orientation="vertical"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<androidx.drawerlayout.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light"
local:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<FrameLayout
android:id="#+id/main_content"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemIconTint="#color/design_default_color_primary"
app:itemTextColor="#color/design_default_color_primary"
app:labelVisibilityMode="labeled"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/navigation" />
</LinearLayout>
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="com.egpaid.employeeapp.home.homedashboard.DrawerFragment"
android:layout_width="260dp"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_drawer"
tools:layout="#layout/fragment_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
</LinearLayout>
</RelativeLayout>
using this code i am able to display data but when i try to click on Home button on either from bottom navigation view or from drawber then i am getting
No view found for id 0x7f0900a3 (com.egpaid.employeeapp:id/fragment_container) for fragment HomeFragment{9d6bf5} (7b531975-d1d4-4ad4-b3c7-6f43ae436c6d) id=0x7f0900a3}
I don't know what i am missing i am trying to create custom navigation drawber with bottom navigation view please help me Thanks

Related

How to combine drawer layout with viewapger2 and Navhostfragment

I try to combine drawer layout with viewapger2 and Navhostfragment. When I clicked the drawer layout icon, NavigationView (that include my menu and header) is opened. whenever ı try to select one item from drawer layout , ı cant select because drawer layout is automatically close. How can ı fix this problem.
this is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.navigation.NavigationView
android:id="#+id/navView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/nav_menu" />
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainerView"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="1dp"
app:defaultNavHost="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:navGraph="#navigation/my_nav" />
</androidx.drawerlayout.widget.DrawerLayout>
</layout>
fragment_view_pager.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/beach4"
android:id="#+id/cons"
tools:context=".view.ViewPagerFragment">
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/view_pager"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="75dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tab_layout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#00ffffff"
android:layout_marginTop="40dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/cons"
app:tabBackground="#drawable/tab_pager_selector"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"
app:tabPaddingEnd="#dimen/tab_padding_end"
app:tabPaddingStart="#dimen/tab_padding_start"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
NavHeader.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="150dp"
android:background="#B3F6FF">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mustafa"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
nav_menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/firstItem"
android:title="First Item"/>
<item
android:id="#+id/secondItem"
android:title="Second Item"/>
<item
android:id="#+id/thirdItem"
android:title="Third Item"/>
MainActivity.kt
class MainActivity : AppCompatActivity() {
companion object {
var globalList = ArrayList<Float>()
var globalVar3=1
var globalVar = 1
var globalVar2 = 1
lateinit var sharedPreferences: SharedPreferences
lateinit var toggle: ActionBarDrawerToggle
lateinit var navVieww: NavigationView
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sharedPreferences =
this.getSharedPreferences("com.mustafa.horizontalrecycler", Context.MODE_PRIVATE)
toggle = ActionBarDrawerToggle(
this#MainActivity,
drawer_layout,
R.string.Open,
R.string.Close
)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val navView = findViewById<NavigationView>(R.id.navView)
navVieww = navView
navView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.firstItem -> {
Toast.makeText(applicationContext, "First Item Selected", Toast.LENGTH_LONG)
.show()
println("First Item")
}
R.id.secondItem -> {
Toast.makeText(applicationContext, "Second Item Selected", Toast.LENGTH_LONG)
.show()
println("Second Item")
}
R.id.thirdItem -> {
Toast.makeText(applicationContext, "Third Item Selected", Toast.LENGTH_LONG)
.show()
}
}
true
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (toggle.onOptionsItemSelected(item)) {
globalVar3= globalVar3+1
return true
}
return super.onOptionsItemSelected(item)
}
}
viewPagerFragment.kt
class ViewPagerFragment : Fragment() {
private val args by navArgs<ViewPagerFragmentArgs>()
private lateinit var wordViewModel: WordViewModel
var number = 1
private lateinit var tabLayout: TabLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
println("VieewPagerOncreated")
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_view_pager, container, false)
wordViewModel = ViewModelProvider(this).get(WordViewModel::class.java)
wordViewModel.readAllData.observe(viewLifecycleOwner, Observer {
//println(it.size)
})
number = sharedPreferences.getInt("pageNumber", 1)
println(number)
val tabLayout = view.findViewById<TabLayout>(R.id.tab_layout)
val viewPager = view.findViewById<ViewPager2>(R.id.view_pager)
val fragments1: ArrayList<Fragment> = arrayListOf(
WeatherListFragment(),
Location1Fragment(),
Location2Fragment(),
Location3Fragment()
)
val fragments2: ArrayList<Fragment> = arrayListOf(
LocationAddFragment()
)
//(i in number..x) x sayısı locationfragment sayısından bir az olcak
//suan için istediğimiz gibi oldu
for (i in number..2) {
fragments1.removeLast()
}
//fragments1.add(fragments2.get(0))
val adapter =
ViewPagerAdapter(fragments1, requireActivity().supportFragmentManager, lifecycle)
viewPager.adapter = adapter
if (MainActivity.globalVar > 1) {
viewPager.setCurrentItem(args.currentPage, false)
}
TabLayoutMediator(tabLayout, viewPager)
{ tab, position -> }.attach()
// bu kod ile başlıgın ismini değiştirebiliriz
(activity as AppCompatActivity).supportActionBar?.title = "Ingredient Display"
(activity as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)
(activity as AppCompatActivity).navView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.firstItem -> {
println("viewpagerfragment")
Toast.makeText(requireContext(), "First Item Selected", Toast.LENGTH_LONG)
.show()
println("First Item")
}
R.id.secondItem -> {
Toast.makeText(requireContext(), "Second Item Selected", Toast.LENGTH_LONG)
.show()
println("Second Item")
}
R.id.thirdItem -> {
Toast.makeText(requireContext(), "Third Item Selected", Toast.LENGTH_LONG)
.show()
}
}
true
}
return view
}
}

navigation componets: BottomNavigationView and navigationDrawer, In a project android

Good morning, any recommendations to use, navigation componets: BottomNavigationView and NavigationDrawer, In a project android.
This project was based on the Samples for Android Architecture Components repository. This is the repository where I took it out:
https://github.com/mackgaru/architecture-components-samples/tree/main/NavigationAdvancedSample
When clicking on a NavigationDrawer item, the navigation does not work well or the app crashes.
This is my repo, if you want to give me a hand:
https://github.com/mackgaru/nBottom_nDrawer.git
Thank you so much.
BottonNavigationView, NavigationDrawer
Here is the error
Process: com.cocktapp.cocktapp, PID: 27899
java.lang.IllegalArgumentException: Navigation action/destination com.cocktapp.cocktapp:id/action_navigation_home_to_homeDetalleFragment cannot be found from the current destination Destination(com.cocktapp.cocktapp:id/homeDetalleFragment) label=Detalle class=com.cocktapp.cocktapp.ui.home.HomeDetalleFragment
at androidx.navigation.NavController.navigate(NavController.java:938)
at androidx.navigation.NavController.navigate(NavController.java:875)
at androidx.navigation.NavController.navigate(NavController.java:861)
at androidx.navigation.NavController.navigate(NavController.java:849)
at com.cocktapp.cocktapp.ui.MainActivity.onNavigationItemSelected(MainActivity.kt:95)
at com.google.android.material.navigation.NavigationView$1.onMenuItemSelected(NavigationView.java:217)
at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:834)
at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:985)
at com.google.android.material.internal.NavigationMenuPresenter$1.onClick(NavigationMenuPresenter.java:416)
at android.view.View.performClick(View.java:5646)
at android.view.View$PerformClick.run(View.java:22473)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6517)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
MainActivity
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private var currentNavController: LiveData<NavController>? = null
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
private lateinit var drawerLayout: DrawerLayout
private lateinit var viewModelHome: HomeViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
if (savedInstanceState == null) {
setupBottomNavigationBar()
}
setSupportActionBar(binding.includeMainContent.toolbarActivity)
drawerLayout = binding.drawerLayout
val navigationView: NavigationView = binding.navView
val toogle = ActionBarDrawerToggle(this, drawerLayout, binding.includeMainContent.toolbarActivity, R.string.open_navigation, R.string.close_navigation)
drawerLayout.addDrawerListener(toogle)
toogle.syncState()
navigationView.setNavigationItemSelectedListener(this)
}//fin onCreate
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
setupBottomNavigationBar()
}
private fun setupBottomNavigationBar() {
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom_nav)
val navGraphIds = listOf(R.navigation.navigation_home, R.navigation.navigation_add, R.navigation.navigation_card, R.navigation.navigation_pay, R.navigation.navigation_config)
// Setup the bottom navigation view with a list of navigation graphs
val controller = bottomNavigationView.setupWithNavController(
navGraphIds = navGraphIds,
fragmentManager = supportFragmentManager,
containerId = R.id.nav_host_container,
intent = intent
)
// Whenever the selected controller changes, setup the action bar
controller.observe(this, Observer { navController ->
setupActionBarWithNavController(navController)
})
currentNavController = controller
Log.i("controller", "valor es = ${currentNavController!!.value}");
}
override fun onSupportNavigateUp(): Boolean {
Log.i("controller", "support = ${currentNavController?.value?.navigateUp()}");
val navController = findNavController(R.id.nav_host_container)
//return currentNavController?.value?.navigateUp() ?: false
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
if(item.itemId == R.id.nav_camera){
Toast.makeText(this , "Camera Click", Toast.LENGTH_SHORT).show()
//Navigation.findNavController(this, R.id.navigationHome).navigate(R.id.action_navigation_home_to_homeDetalleFragment)
currentNavController?.value?.navigate(R.id.action_navigation_home_to_homeDetalleFragment)
drawerLayout.closeDrawer(Gravity.LEFT)
}
return true;
}
override fun onBackPressed() {
if(drawerLayout.isDrawerOpen(Gravity.LEFT)){
drawerLayout.closeDrawer(Gravity.LEFT)
}else{
super.onBackPressed()
}
}
}
activity_main.xml
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
android:id="#+id/include_main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
layout="#layout/dra_main_content_appbar"/>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/dra_drawer_nav_header"
app:menu="#menu/drawer_navigation" />
</androidx.drawerlayout.widget.DrawerLayout>
dra_main_content_appbar
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.Cocktapp.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar_activity"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/Theme.Cocktapp.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="#layout/dra_content" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
dra_content
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/dra_main_content_appbar">
<androidx.fragment.app.FragmentContainerView
android:id="#+id/nav_host_container"
android:name="androidx.navigation.fragment.NavHostFragment"
app:defaultNavHost="true"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
Each element of the BottonNavigationView has a different navigation file: example: navigation_home
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/navigationHome"
app:startDestination="#id/navigation_home">
<fragment
android:id="#+id/navigation_home"
android:name="com.cocktapp.cocktapp.ui.home.HomeFragment"
android:label="Home"
tools:layout="#layout/fragment_home" >
<action
android:id="#+id/action_navigation_home_to_homeDetalleFragment"
app:destination="#id/homeDetalleFragment" />
</fragment>
<fragment
android:id="#+id/homeDetalleFragment"
android:name="com.cocktapp.cocktapp.ui.home.HomeDetalleFragment"
android:label="Detalle"
tools:layout="#layout/fragment_home_detalle" />
</navigation>
example: navigation_add
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/navigationAdd"
app:startDestination="#id/navigation_add">
<fragment
android:id="#+id/navigation_add"
android:name="com.cocktapp.cocktapp.ui.add.AddFragment"
android:label="Nuevo"
tools:layout="#layout/fragment_add" >
<action
android:id="#+id/action_navigation_add_to_addDetallekFragment"
app:destination="#id/addDetalleFragment" />
</fragment>
<fragment
android:id="#+id/addDetalleFragment"
android:name="com.cocktapp.cocktapp.ui.add.AddDetalleFragment"
android:label="Detalle"
tools:layout="#layout/fragment_add_detalle" />
</navigation>
All you have to do is:
override fun onNavigationItemSelected(item: MenuItem): Boolean {
if(item.itemId == R.id.nav_camera){
Toast.makeText(this , "Camera Click", Toast.LENGTH_SHORT).show()
if(currentNavController.currentDestination.id != R.id.homeDetalleFragment){
currentNavController?.value?.navigate(R.id.action_navigation_home_to_homeDetalleFragment)
}
drawerLayout.closeDrawer(Gravity.LEFT)
}
return true;
}

how to I call fragment from fragment with bottomnavigationview - Kotlin

I have got problems.
There are 5 fragment in MainActivity. It is D1, D2, D3, D4, D5 Fragment. And there is BottomNavigationView in MainActivity. I want to call DxFragment from D1fragment. The button will be clicked and only the frame will change. But the button navigation bar will not change.
I've been looking for a while. I couldn't find the solution. Can anyone please help?
MAINACTIVITY
class MainActivity : AppCompatActivity() {
private lateinit var bottomNavigationView : BottomNavigationView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bottomNavigationView = findViewById(R.id.nav_view)
navigateFragment(false)
}
public fun loadFragment (fragment: Fragment){
supportFragmentManager.beginTransaction().also { fragmentTransaction ->
fragmentTransaction.replace(R.id.bottom_nav_host_fragment, fragment)
fragmentTransaction.commit()
}
}
public fun navigateFragment ( stateFragment : Boolean) {
bottomNavigationView = findViewById(R.id.nav_view)
bottomNavigationView.setOnNavigationItemSelectedListener { menuItem : MenuItem ->
when{
menuItem.itemId== R.id.navigation_home -> {
loadFragment(D1Fragment())
return#setOnNavigationItemSelectedListener true
}
menuItem.itemId == R.id.navigation_map -> {
loadFragment(D2Fragment())
return#setOnNavigationItemSelectedListener true
}
menuItem.itemId == R.id.navigation_userpage -> {
loadFragment(D3Fragment())
return#setOnNavigationItemSelectedListener true
}
menuItem.itemId == R.id.navigation_fav -> {
loadFragment(D4Fragment())
return#setOnNavigationItemSelectedListener true
}
menuItem.itemId == R.id.navigation_list -> {
loadFragment(D5Fragment())
return#setOnNavigationItemSelectedListener true
}
stateFragment == true -> {
loadFragment(BlankFragment())
return#setOnNavigationItemSelectedListener true
}
else -> {
return#setOnNavigationItemSelectedListener true
}
}
}
}
override fun onSupportNavigateUp(): Boolean {
return Navigation.findNavController(this, R.id.bottom_nav_host_fragment).navigateUp() ||
super.onSupportNavigateUp()
}
}
ACTIVITY_MAIN.XML
some part
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_menu" />
<FrameLayout
android:id="#+id/bottom_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#id/nav_view"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
FRAGMENT_D1.XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".D1Fragment">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CLICK AND GO BLANKFRAGMENT" />
</FrameLayout>
D1FRAGMENT
class D1Fragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_d1, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
button.setOnClickListener {
Toast.makeText(context , "CLICKED" , Toast.LENGTH_SHORT ).show()
Navigation.findNavController(view).navigate(R.id.action_d1Fragment_to_blankFragment)
}
super.onViewCreated(view, savedInstanceState)
}
}
BUTTON CLICK AND ERROR
java.lang.IllegalStateException: View android.widget.FrameLayout{16424ce5 V.E..... ........ 0,0-1080,1365} does not have a NavController set
at androidx.navigation.Navigation.findNavController(Navigation.java:84)
at com.axisting.bottomelledeneme.D1Fragment$onViewCreated$1.onClick(D1Fragment.kt:35)
You only needs to have a principal class,
Example main's activity, it contains the BottomNavigationView and fragment. the fragments have the other element
Example
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.con straintlayout.widget.ConstraintLayout>
You only need to attach the fragment

Data is not loading in HomeFragment after using different menu in BottomNavigationView in Android

I am fetching data from network and showing in my list. I am using BottomNavigationView in Main Screen. It shows 4 tabs. When i launch the app, data is loading in Home screen but when i go to some other tab in Bottom navigation view and comeback to home tab, Data is not loading. In Home Screen has view pager tabs.
MainActivity.kt
class MainActivity : AppCompatActivity(), BottomNavigationView.OnNavigationItemSelectedListener {
lateinit var tabs: TabLayout
lateinit var toolbar: Toolbar
lateinit var sharedPreferences: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sharedPreferences = getSharedPreferences(AppConstants.PREF_NAME, Context.MODE_PRIVATE)
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
toolbar.setTitle(R.string.app_name)
val navigationView1: BottomNavigationView = findViewById(R.id.nav_view)
navigationView1.setOnNavigationItemSelectedListener(this)
if (savedInstanceState == null) {
loadFragment(MainFragment())
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
var fragment: Fragment? = null
when (item.itemId) {
R.id.news -> {
invalidateOptionsMenu()
fragment = MainFragment()
}
R.id.source -> {
fragment = SourcesFragment()
toolbar.getMenu().clear()
toolbar.setTitle("News Sources")
}
R.id.save -> {
toolbar.setTitle("Saved Articles")
toolbar.getMenu().clear()
fragment = WatchListFragment()
}
R.id.settings -> {
toolbar.setTitle("Settings")
toolbar.getMenu().clear()
fragment = SettingsFragment()
}
}
loadFragment(fragment)
return true
}
private fun loadFragment(fragment: Fragment?) {
val transaction = supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.design_bottom_sheet_slide_in, R.anim.design_bottom_sheet_slide_out)
transaction.replace(R.id.container, fragment!!)
transaction.commit()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_search -> {
startActivity(Intent(this, SearchActivity::class.java))
}
else -> ""
}
return true
}
}
MainFragment.kt
class MainFragment : Fragment() {
lateinit var tabs: TabLayout
lateinit var pager: ViewPager
lateinit var adapter: PagerAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
var view = inflater.inflate(R.layout.fragment_main, container, false)
pager = view.findViewById(R.id.viewpager)
setupViewPager(pager)
pager.addOnPageChangeListener(onPageChangeListener)
tabs = view.findViewById(R.id.tabs)
tabs.setupWithViewPager(pager)
Log.d("LIVE", "onCreateView")
return view
}
private fun setupViewPager(pager: ViewPager) {
adapter = PagerAdapter(fragmentManager!!)
adapter.addFragment(TopNewsFragment(), "Top News")
adapter.addFragment(TechnologyFragment(), "Technology")
adapter.addFragment(BusinessFragment(), "Business")
adapter.addFragment(SportsFragment(), "Sports")
adapter.addFragment(EntertainmentFragment(), "Entertainment")
adapter.addFragment(ScienceFragment(), "Science")
adapter.addFragment(HealthFragment(), "Health")
pager.adapter = adapter
adapter.notifyDataSetChanged()
}
private val onPageChangeListener = object : ViewPager.OnPageChangeListener {
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
adapter.notifyDataSetChanged()
}
override fun onPageScrollStateChanged(state: Int) {
}
}
}
fragment_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
style="#style/Widget.MaterialComponents.TabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="10dp"
app:tabGravity="center"
app:tabIndicatorColor="#color/tab_selected_color"
app:tabMode="scrollable"
app:tabSelectedTextColor="#color/tab_selected_color"
app:tabTextColor="#color/textColorPrimary" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
</FrameLayout>
activity_main.xml
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay"
app:elevation="10dp">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:elevation="4dp"
app:itemIconTint="#drawable/bottom_navigation_text_color"
app:itemTextColor="#drawable/bottom_navigation_text_color"
app:labelVisibilityMode="labeled"
app:menu="#menu/bottom_navigation_menu" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Home Screen
DataNotloading
Updated Code:
class MainActivity : AppCompatActivity(), BottomNavigationView.OnNavigationItemSelectedListener {
lateinit var tabs: TabLayout
lateinit var toolbar: Toolbar
lateinit var sharedPreferences: SharedPreferences
private val mNewsFragment = MainFragment()
private val mSourceFragment: SourcesFragment = SourcesFragment()
private val mSaveFragment: WatchListFragment = WatchListFragment()
private val mSettingFragment = SettingsFragment()
var activeFragment: Fragment= MainFragment()
val fm: FragmentManager = supportFragmentManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sharedPreferences = getSharedPreferences(AppConstants.PREF_NAME, Context.MODE_PRIVATE)
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
toolbar.setTitle(R.string.app_name)
val navigationView1: BottomNavigationView = findViewById(R.id.nav_view)
navigationView1.setOnNavigationItemSelectedListener(this)
fm.beginTransaction().add(R.id.container, activeFragment).commit();
fm.beginTransaction().add(R.id.container, mSettingFragment).hide(mSettingFragment).commit();
fm.beginTransaction().add(R.id.container, mSourceFragment).hide(mSourceFragment).commit();
fm.beginTransaction().add(R.id.container, mSaveFragment).hide(mSaveFragment).commit();
/* if (savedInstanceState == null) {
val transaction = supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.design_bottom_sheet_slide_in, R.anim.design_bottom_sheet_slide_out)
transaction.add(R.id.container, activeFragment).commit();
transaction.add(R.id.container, activeFragment).hide(activeFragment).commit();
transaction.add(R.id.container, activeFragment).hide(activeFragment).commit();
}*/
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
var fragment: Fragment? = null
when (item.itemId) {
R.id.news -> {
invalidateOptionsMenu()
fragment = MainFragment()
toolbar.getMenu().clear()
toolbar.setTitle("News Headlines")
}
R.id.source -> {
fragment = SourcesFragment()
toolbar.getMenu().clear()
toolbar.setTitle("News Sources")
}
R.id.save -> {
toolbar.setTitle("Saved Articles")
toolbar.getMenu().clear()
fragment = WatchListFragment()
}
R.id.settings -> {
toolbar.setTitle("Settings")
toolbar.getMenu().clear()
fragment = SettingsFragment()
}
}
loadFragment(fragment)
return true
}
private fun loadFragment(fragment: Fragment?) {
val transaction = supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.design_bottom_sheet_slide_in, R.anim.design_bottom_sheet_slide_out).hide(activeFragment).show(fragment!!).commit();
activeFragment = fragment;
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.action_search -> {
startActivity(Intent(this, SearchActivity::class.java))
}
else -> ""
}
return true
}
}
You need to Add
pager.setOffscreenPageLimit(2)
After
pager = view.findViewById(R.id.viewpager)
For details
https://developer.android.com/reference/android/support/v4/view/ViewPager#setoffscreenpagelimit
UPDATE
As per new findings, when you swipe between fragments, your fragment state is saved.It is saved because when you swipe, Viewpager comes into action. And when you set pager.setOffscreenPageLimit(2), 2 fragments on either side are saved.Hence you have no issues with swiping.
But when you choose a fragment using BottomNavigationView, you are using replace. replace method removes a fragment from a container so onCreate() will get executed each time when user switches the tabs.
Using the following code for BottomNavigationView, you can solve this issue.
Bottom Line : Instead of Creating/replacing new fragments with BottomNavigationView, you can use hiding.
MainActivity
Declare a fragment variable like that
Fragment activeFragment= new MainFragment();
In onCreate, after setContentView, hide all fragments and commit them to the fragment manager, but do not hide the first fragment that will serve as home fragment.
fm.beginTransaction().add(R.id.main_container,fragment1).commit();
fm.beginTransaction().add(R.id.main_container, fragment2).hide(fragment2).commit();
fm.beginTransaction().add(R.id.main_container, fragment3).hide(fragment3).commit();
Replace your loadFragment() like that.
private fun loadFragment(fragment: Fragment?) {
val transaction = supportFragmentManager.beginTransaction()
.setCustomAnimations(R.anim.design_bottom_sheet_slide_in, R.anim.design_bottom_sheet_slide_out).hide(activeFragment).show(fragment).commit();
transaction.commit()
activeFragment=fragment;
}
2ND UPDATE
Replace
fm.beginTransaction().add(R.id.main_container,fragment1).commit();
With
fm.beginTransaction().add(R.id.main_container,activeFragment).commit();

How can I combine a bottom navigation view, a Tablayout and a Viewpager in Android Kotlin?

I've been trying to combine a bottom navigation view, a tablayout and a viewpager. I already have the tableyout working with the viewpager, but when selecting another item (different from the one containing the tableyout) from the bottom navigation view nothing happens and it seems that they were disabled. I do not know what I'm doing wrong. I am a novice on Android.
I want something like this:
MainActivity.kt
class MainActivity : AppCompatActivity() {
private val onNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_data_sheet -> {
replaceFragment(DataSheetFragment())
return#OnNavigationItemSelectedListener true
}
R.id.navigation_search -> {
replaceFragment(SearchFragment())
return#OnNavigationItemSelectedListener true
}
R.id.navigation_notifications -> {
replaceFragment(NotificationsFragment())
return#OnNavigationItemSelectedListener true
}
R.id.navigation_profile -> {
val intent = Intent(this#MainActivity, NoLoginActivity::class.java)
startActivity(intent)
finish()
return#OnNavigationItemSelectedListener true
}
}
false
}
private fun replaceFragment(fragment: Fragment) {
val fragmentTransition = supportFragmentManager.beginTransaction()
fragmentTransition.replace(R.id.fragmentContainer, fragment)
fragmentTransition.commit()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
replaceFragment(DataSheetFragment())
val navView: BottomNavigationView = findViewById(R.id.bottom_navigation)
navView.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener)
}}
PagerAdapter.kt
class PagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when (position) {
0 -> {
SpecimensFragment()
}
else -> {
return FungiFragment()
}
}
}
override fun getCount(): Int {
return 2
}
override fun getPageTitle(position: Int): CharSequence {
return when (position) {
0 -> "Especímenes"
else -> {
return "Hongos"
}
}
}}
DataSheetFragment.kt: Fragment que contiene el tablayout
class DataSheetFragment : Fragment() {
private lateinit var viewPager: ViewPager
private lateinit var tabs: TabLayout
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view: View = inflater.inflate(R.layout.fragment_data_sheet, container, false)
viewPager = view.findViewById(R.id.viewPager)
tabs = view.findViewById(R.id.data_sheet_tabs)
val fragmentAdapter = PagerAdapter(childFragmentManager)
viewPager.adapter = fragmentAdapter
tabs.setupWithViewPager(viewPager)
return view
}}
fragment_data_sheet.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".Fragments.DataSheetFragment"
>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:title="#string/data_sheet"
app:titleTextColor="#color/white"
android:background="#color/colorPrimary"
>
</androidx.appcompat.widget.Toolbar>
<com.google.android.material.tabs.TabLayout
android:id="#+id/data_sheet_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/toolbar"
android:background="#color/background_color"
app:tabTextAppearance="#style/TabLayoutTextAppearance"
>
<com.google.android.material.tabs.TabItem
android:id="#+id/specimens_tab"
android:text="#string/specimens"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<com.google.android.material.tabs.TabItem
android:id="#+id/fungi_tab"
android:text="#string/fungi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#id/data_sheet_tabs"
/>
</androidx.constraintlayout.widget.ConstraintLayout>

Categories

Resources