Android simple example of opening Fragments Anywhere using navGraph

By | August 20, 2020

In this tutorial,we are showing different ways to opening fragment using navGraph. We are using android latest technology(navGraph) for creating navigation drawer. navGraph automatically handle all navigation of fragments we don’t need to take care of this .By default every drawer menu open a fragment.Now if you want to open fragment from another fragment or open fragment anywhere in the app. Below example will show how to achieve this.

Creating Project

We will create NEW android project with Navigation Drawer Activity.

And we will get 3 drawer menu Home,Gallery,Slideshow. And all related files for creating navigation Drawer.

Now you can run your app and check when you click on navigation drawer menu respected Fragment will open.

1: Open Fragment From Another Fragment

We will create a button Open Gallery in home fragment and it will open Gallery fragment.

STEP 1.1 Create Button inside Home fragment

fragment_home.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"
tools:context=".ui.home.HomeFragment">

<TextView
android:id="@+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textSize="20sp"
android:gravity="center_horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.326" />

<Button
android:id="@+id/gallery_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="76dp"
android:gravity="center_horizontal"
android:text="Open Gallery"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/text_home" />
</androidx.constraintlayout.widget.ConstraintLayout>

STEP 1.2 Creating Action

navGraph uses Action for redirecting fragment to another fragment.

Open file: navigation/mobile_navigation.xml. This is your navGraph ,here we will create action.

Click on nav_home >select Round Point>drag and drop into nav_gallery. Now An action will automatically created named action_nav_home_to_nav_gallery (we will use this action name to open gallery fragment from home fragment).

STEP 1.3 HomeFragment.java

here we open Gallery Fragment in Open Gallery button’s Onclick method.

In navigate(…) method we pass the action id.

NavHostFragment.findNavController(HomeFragment.this).navigate(R.id.action_nav_home_to_nav_gallery);
package com.khushi.navigation.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.fragment.NavHostFragment;

import com.khushi.navigation.R;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        final TextView textView = view.findViewById(R.id.text_home);
        Button GalleryButton =view.findViewById(R.id.gallery_button);
        GalleryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //here we open gallery fragment
                NavHostFragment.findNavController(HomeFragment.this).navigate(R.id.action_nav_home_to_nav_gallery);
            }
        });

        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return view;
    }
}

2: Open Fragment From Activity

Here we open Slideshow fragment from menu.

STEP 2.1 Create menu item Slideshow

Open file: menu/main.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_slideshow"
android:orderInCategory="100"
android:title="@string/menu_slideshow"
app:showAsAction="never" />
</menu>

STEP 2.2 MainActivity.java

Inflate main.xml menu by overriding this method.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

Get which menu item is clicked by overriding this method.

here we open fragment_slideshow if Slideshow menu item clicked.


@Override
public boolean onOptionsItemSelected(MenuItem item) {
int currentMenu = item.getItemId();
switch (currentMenu) {
case R.id.action_slideshow:
navController.navigate(R.id.nav_slideshow);
}
return true;
}

Complete code of MainActivity.java

package com.khushi.navigation;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    NavController navController;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
                .setDrawerLayout(drawer)
                .build();
        navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int currentMenu = item.getItemId();
        switch (currentMenu) {
            case R.id.action_slideshow:
                navController.navigate(R.id.nav_slideshow);
        }
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

592 total views, 3 views today

(Visited 89 times, 1 visits today)