Grace Tanya
Grace Tanya

Reputation: 13

How to switch between fragments using button under navigation activity

I'm just new on Android Studio so please bear with me. I created two fragments named locate_before and locate_after. I have a button with an id of trigger on my locate_before fragment. I want to switch to locate_after after clicking that button.

Here's my main activity. I used a frame container for my fragments. I already created a code for what I want named onSelectFragment but it does not work. It says "method onSelectFragment is never used"

import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    Button trigger;

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

        //Set the fragment initially
        locate_before fragment = new locate_before();
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction(); //check this out

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

    public void onSelectFragment(View v){
        Fragment newFragment;

        if(v == findViewById(R.id.trigger)){
            newFragment = new locate_after();
        }
        else{
            newFragment = new locate_before();
        }

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }



    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @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) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

}

locate_before fragment java that ofc extends Fragment

public locate_before () {
        // Required empty public constructor

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_locate_before, container, false);

        // Inflate the layout for this fragment
        return rootView;
    }
}

locate_before xml file button

 <Button
        android:id="@+id/trigger"
        android:layout_width="284dp"
        android:layout_height="58dp"
        android:text="View Car's Location"
        android:layout_marginRight="24dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.633"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="133dp" />

locate_after java

public class locate_after extends Fragment {


    public locate_after () {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_locate_after, container, false);

        // Inflate the layout for this fragment
        return rootView;
    }
}

Thank you!

Upvotes: 0

Views: 3453

Answers (5)

Suresh Kumar
Suresh Kumar

Reputation: 2034

Check current displayed fragment and set your desired fragment accordingly. Try the below code.

        Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_container);
        if(!(fragment instanceof locate_before)) {
            newFragment = new locate_after();
        }
        else{
            newFragment = new locate_before();
        }
        getSupportFragmentManager().beginTransaction().replace(newFragment).commit();

Upvotes: 0

Fragile
Fragile

Reputation: 51

First of all, you are never using method OnSelectFragment(). In your OnCreate method add following

trigger = (Button) findViewById(R.id.trigger); //get Button
trigger.setOnClickListener(new View.OnClickListener() { // action to do when button is pressed
        @Override
        public void onClick(View view) {
            if(before)
                onSelectFragment(new locate_after());
            else
                onSelectFragment(new locate_before());
            before = !before; //this makes it a switch
        }
    });

Declare attribute "before" along other attributes

boolean before = true;

And change your onSelectFragment method to following

 public void onSelectFragment(Fragment newFragment){

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

Upvotes: 0

G00fY
G00fY

Reputation: 5277

Your buttom seems to have no onClickListener.

Add android:onClick="onSelectFragment" in your XML or bind your Button and add an onClickListener in your OnCreate.

Upvotes: 1

Kishor N R
Kishor N R

Reputation: 1591

use onNavigationItemSelected() to navigate to fragment. below is the examples code

@Override
public boolean onNavigationItemSelected(MenuItem item) {

    // Handle navigation view item clicks here.
    int id = item.getItemId();

    FragmentManager fragmentManager = getSupportFragmentManager();

    if (id == R.id.nav_home) {
        Fragment homeFragment = new HomeFragment();
        fragmentManager.beginTransaction().replace(R.id.relative_layout_fragment1, homeFragment, homeFragment.getTag()).commit();

    }  else if (id == R.id.nav_logout) {

        Toast.makeText(mContext, "logout", Toast.LENGTH_SHORT).show();
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

Upvotes: 1

Anton Potapov
Anton Potapov

Reputation: 1275

You have uncommited transaction after your onCreate()

FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction(); //check this out

Upvotes: 0

Related Questions