Kuba
Kuba

Reputation: 53

get data from Navigation Activity in Navigation library

I'm using Navigation library from Architecture Components where in MainActivity I setup navigation and Toolbar as main Toolbar for whole app. In navigation.xml file I setup app:startDestination for one of fragments. Is it possible to get data about Toolbar which is lockated in MainActivity while I am already in launched fragment?

MainActivity:

ublic class MainActivity extends AppCompatActivity {
private NavigationActivityBinding binding;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding = DataBindingUtil.setContentView(this, R.layout.navigation_activity);
    NavHostFragment hostFragment =
            (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.my_nav_host_fragment);
    setSupportActionBar(binding.toolbar);

    NavController navController = hostFragment.getNavController();
    setupActionBar(navController);
    setupBottomNavigation(navController);
}

private void setupBottomNavigation(NavController navController) {
    NavigationUI.setupWithNavController(binding.bottomNavView, navController);
}

private void setupActionBar(NavController navController) {
    NavigationUI.setupActionBarWithNavController(this, navController, null);
}}

navigation.xml:

<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"
app:startDestination="@+id/launcher_home">
<fragment
    android:id="@+id/launcher_home"
    android:name="josiak.android.example.cryptocurrency.charts.ui.CryptocurrencyMainList"
    android:label="fragment_cryptocurrency_main_list"
    tools:layout="@layout/fragment_cryptocurrency_main_list" />

Upvotes: 0

Views: 819

Answers (2)

Alex
Alex

Reputation: 9352

You can add addOnNavigatedListener inside your activity, and based on current destination do something with toolbar. If you want to pass some data to current fragment, you can use viewmodel attached to activity, and set parameters/states, to which fragment is listening.

findNavController(nav_host_fragment).addOnNavigatedListener { controller, 
destination ->
    when(destination.id) {
        R.id.destination1 -> {
            //Do something with your toolbar
        }
        R.id.destination2 -> {
            //Do something with your toolbar
        }

 }
}

Upvotes: 1

Kuba
Kuba

Reputation: 53

When I tried to ((MainActivity).getActivity()).getSupportActionBar() in fragment lifecycle method onActivityCreated() it returned null value for getHeight() but when I tried to do ((MainActivity).getActivity()).getSupportActionBar().getHeight() when I click button/menu item, it works. Seems like I can get height of action bar only after fragment is activated.

Upvotes: 1

Related Questions