AhChing11
AhChing11

Reputation: 155

I have only a Single Activity in my Android Project and I want to show different type of Menu in different Fragment

My Android Projects implements only One activity and others are all Fragments. So, for example i have 5 Fragments, I want 3 of them having a BottomNavigation menu while the other 2 to have TabLayout menu. How can i do that? I saw some people say create an Interface and let my MainActivity implement the Interface, then make changes to Activity from Fragment through Interface. Is this the best choice/practice? What other options is available and which is the best?

Upvotes: 0

Views: 94

Answers (3)

AhChing11
AhChing11

Reputation: 155

Solution 1:

First, create a function in my MainActivity. Below is my project's code as an example. I modifed the layout programatically and all is written in this showTabLayoutUI() function.

fun showTabLayoutUI() {
        Log.d(TAG, "showTabLayoutUI: initiated")

        infix fun View.below(view:View) {
            var layoutParam = this.layoutParams as? RelativeLayout.LayoutParams
            layoutParam?.addRule(RelativeLayout.BELOW, view.id)
            layoutParam?.removeRule(RelativeLayout.ALIGN_PARENT_TOP)
        }
        binding.bottomNav.visibility = View.GONE //Hide Bottom Nav
        binding.sellerSiteActionBarRl.visibility = View.VISIBLE //Show Action Bar
        binding.sellerSiteTl.visibility = View.VISIBLE //Show Tab Layout

        binding.fragmentContainerView.below(binding.sellerSiteTl)
    }

Then in my Fragment, I call the method in the MainActivity by using this code:

(activity as MainActivity?)!!.showTabLayoutUI()

It will then hide the bottomNav and show the TabLayout.

Solution 2: If Navigation Component is used, then in your MainActivity, you can check which Fragment is currently being displayed by typing:

navController.addOnDestinationChangedListener{_, destiantion, _ ->
    if(destination.id == R.id.fragmentOne) {
        //display BottomNavigation
    } else if (destination.id == R.id.fragmentTwo) {
        //display TabLayout
    }

Upvotes: 0

DHoogerwaard
DHoogerwaard

Reputation: 758

An interface is not necessary to handle this usecase. You can create both Views in your Activity and simply set the visibility when you create a new Fragment. view.visibility = View.VISIBLE view.visibility = View.GONE.

Upvotes: 1

Ameen Essa
Ameen Essa

Reputation: 124

You can try to implement it using Jetpack Navigation component, it will be easier to handle.

Check the official document

Upvotes: 1

Related Questions