Tony Starkus
Tony Starkus

Reputation: 576

Start fragment in BottomNavigationView

I'm working with a simple app with Bottom Navigation View. I have 3 fragment with text, and i want to start their when i select a item in Botton Navigation, but i don't know what to write in the MainActivity.java; All the fragments have a .xml layout and .java. I searched in some codes, i wrote them, i search videos, but i have no sucess.

I'm learning about Fragments and UI Dynamic, so i created a new project in Android Studio with Bottom Navigation Activity. So, in my activity_main i have 3 itens in Bottom Navigation, and one framelayout above Bottom Navigation, taking all the parent. The idea is: when i select a item in Bottom Navigation, it will show another layout in the framelayout. So i created 3 xml layouts (with java class too) in layout folder and one fragment in framelayout. Now, i'm trying to show these layouts in my framelayout(that have a fragment) when i select a item. But i don't know how to do that.

Main Activity`

private TextView mTextMessage;

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment selectedFragment = null;
        switch (item.getItemId()) {
            case R.id.navigation_home:
                selectedFragment = HomeFragment.newInstance();
                break;
            case R.id.navigation_dashboard:
                selectedFragment = DashboardFragment.newInstance();
                break;
            case R.id.navigation_notifications:
                selectedFragment = NotificationsFragment.newInstance();
                break;
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content, selectedFragment);
        transaction.commit();
        return true;
    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.content, HomeFragment.newInstance());
    transaction.commit();
}

activity_main xml

<LinearLayout
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/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="bandeira.thalisson.barradenavegacaoembaixo.MainActivity">

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1">
</FrameLayout>

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="?android:attr/windowBackground"
    app:menu="@menu/navigation"/>

navigation xml

<item
    android:id="@+id/Fragment_one"
    android:icon="@drawable/ic_home_black_24dp"
    android:title="@string/title_home"/>

<item
    android:id="@+id/Fragment_two"
    android:icon="@drawable/ic_dashboard_black_24dp"
    android:title="@string/title_dashboard"/>

<item
    android:id="@+id/Fragment_three"
    android:icon="@drawable/ic_notifications_black_24dp"
    android:title="@string/title_notifications"/>

Fragment.java example

public class HomeFragment extends Fragment {

public static HomeFragment newInstance() {
    HomeFragment fragment = new HomeFragment();
    return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.navigation_home, container, false);
    return inflater.inflate(R.layout.navigation_home, container, false);
}

Upvotes: 3

Views: 8969

Answers (4)

Leonardo Pineda
Leonardo Pineda

Reputation: 1028

alone with create this methor

protected boolean openFragment(Fragment fragment){
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.content, fragment)
            .commit();
    return true;
}

to edit in the switch

public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_home: return openFragment(OneFragment.newInstance("",""));
            case R.id.navigation_beehive: return openFragment(twoFragment.newInstance("",""));
            case R.id.navigation_notifications: return openFragment(otherFragment.newInstance("",""));
        }
        return false;
    }

and for to finalize you can to initialize with a fragment in

 protected void onCreate(Bundle savedInstanceState) {
    ....
    openFragment(OneFragment.newInstance("",""));
}

Upvotes: 1

ZooMagic
ZooMagic

Reputation: 666

I would just add, if you wanted to use your BottomNavigationView.OnNavigationItemSelectedListener()to select your start fragment you can use the setSelectedItemId() e.g. :

Replace 'R.id.navigation_home' with your own start fragment.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BottomNavigationView navigation = (BottomNavigationView) 
    findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    navigation.setSelectedItemId(R.id.navigation_home);
}

Upvotes: 1

Akshay Nandwana
Akshay Nandwana

Reputation: 1292

Firstly, in your activity_main.xml we don't require 3 different fragments as we can replace or add our any selected Fragment in 1 FrameLayout only. Secondly, when ever the user select any one from the Bottom NavigationView just get an instance of the related Fragment class and replace it with your activity_main's FrameLayout .

Fragment selectedFragment = null;
         switch (item.getItemId()) {
               case R.id.navigation_home:
                   selectedFragment = FunFragment.newInstance();
                   break;

after getting the instance of the selected Fragment replace it with you activity_main's FrameLayout as to show on the screen.

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.content, selectedFragment);
            transaction.commit();

EDIT TAG Step 1. your activity_main.xml should look like this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.exampl.MainActivity">
    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>
    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="?android:attr/windowBackground"
        app:menu="@menu/navigation" />
</LinearLayout>

Step 2. Your fragment_home.xml layout should be like this

 <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="android"/>
    </LinearLayout>

Make 3 different fragment layout for your three different options

Step 3. your MainActivity.java class will be like this

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
                = new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                Fragment selectedFragment = null;
                switch (item.getItemId()) {
                    case R.id.navigation_home:
                        selectedFragment = FunFragment.newInstance();
                       break;
                    case R.id.navigation_dashboard:
                        selectedFragment = TheoryFragment.newInstance();
                       break;
                    case R.id.navigation_notifications:
                        selectedFragment = AndroidFragment.newInstance();
                        break;
                }
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.content, selectedFragment);
                transaction.commit();
                return true;
            }
        };

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content, FunFragment.newInstance());
        transaction.commit();
    }

In on create replace with the fragment which you want to show after launching the application and navigation listener will take care of what ever option you will select

Step 4. Your will have 3 different Fragment class and look like this

public class TheoryFragment extends Fragment {

     public static TheoryFragment newInstance() {
            TheoryFragment fragment = new TheoryFragment();
            return fragment;
        }
     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_theory, container, false);
            unbinder = ButterKnife.bind(this, rootView);
            return rootView;
        }
    }

Hope it will help you, let me know if any problem.

Upvotes: 3

Sabyasachi
Sabyasachi

Reputation: 3599

Take three Fragments like HomeFragment,DashboardFragment and NotificationFragment and three layouts for those three fragments.

HomeFragment

public class HomeFragment extends Fragment {
    public HomeFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }
}

fragment_home.xml

<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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home Fragment"
        android:textStyle="bold"
        android:layout_gravity="center"/>
</FrameLayout>

**DashboardFragment **

public class DashboardFragment extends Fragment {
    public DashboardFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_dashboard, container, false);
    }
}

fragment_dashboard.xml

<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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dashboard Fragment"
        android:textStyle="bold"
        android:layout_gravity="center"/>
</FrameLayout>

**NotificationFragment **

public class NotificationFragment extends Fragment {
    public NotificationFragment () {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_notification, container, false);
    }
}

fragment_notification.xml

<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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Notification Fragment"
        android:textStyle="bold"
        android:layout_gravity="center"/>
</FrameLayout>

This is Your activity.

public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();
                switch (id){
                    case R.id.Fragment_one:
                        fragment = new HomeFragment();
                        break;
                    case R.id.Fragment_two:
                        fragment = new DashboardFragment();
                        break;
                    case R.id.Fragment_three:
                        fragment = new NotificationFragment();
                        break;
                }
                final FragmentTransaction transaction = fragmentManager.beginTransaction();
                transaction.replace(R.id.main_container, fragment).commit();
                return true;
            }
        });

Upvotes: 3

Related Questions