How to switch between fragments using button under navigation activity - android

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!

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.

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;
}

You have uncommited transaction after your onCreate()
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction(); //check this out

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();
}

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();

Related

how to minimize the map in the google maps activity? [duplicate]

I am relatively new to Coding but please bear with me. I am trying to put a Google Map in a navigation drawer. I figured the best way is to use fragments but despite my various attempts I keep getting this error: "Error:(35, 62) error: incompatible types: MapsActivity cannot be converted to Fragment".
I have two Activities
1. MainActiyity: where there's an error.
2. MapsActivity: which is the default Activity when choosing to create google maps app on Android studio new project creation.
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
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.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set to start with fragment
MapsActivity fragment = new MapsActivity();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) 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 = (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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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();
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_building) {
MapsActivity fragment = new MapsActivity();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_map) {
} else if (id == R.id.nav_timetable) {
} else if (id == R.id.nav_noticeboard) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_placeholder) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Also, the word 'fragment' in fragmentTransaction.replace(R.id.fragment_container, fragment);
is underlined red.
I have tried to find different tutorials and guides but nothing solved my issue.
You can't do a FragmentTransaction with an Activity.
In order to use a Google Map in a NavigationDrawer, use a Fragment that extends SupportMapFragment, and add all of the functionality that your MapsActivity class currently has.
Use this to start with:
public class MapsFragment extends SupportMapFragment
implements OnMapReadyCallback {
GoogleMap mGoogleMap;
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mGoogleMap == null) {
getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap=googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
}
Then in the Activity, change this to use the Fragment:
// Set to start with fragment
MapsFragment fragment = new MapsFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();

Fragment doesn't replace in Navigation Drawer

I'm creating a Navigation Drawer like this
MainActivity.java
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
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 com.paperwrrk.videos.FragmentVideo;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) 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 = (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);
}
#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();
FragmentManager fragmentManager = getSupportFragmentManager();
if (id == R.id.nav_home) {
// Handle the camera action
} else if (id == R.id.nav_articles) {
} else if (id == R.id.nav_videos) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame, new FragmentVideo())
.addToBackStack(null)
.commit();
} else if (id == R.id.fb_posts) {
} 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;
}
}
My FragmentVideo
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.paperwrrk.R;
public class FragmentVideo extends Fragment {
View myView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
myView = inflater.inflate(R.layout.fragment_video, container, false);
return myView;
}
}
But when I click on the item from Navigation Drawer second fragment doesn't replace or hide the first one, it is overlapping like this
Please see the screenshot
Use a container instead of using fragment tag
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Hello World!" />
Now in activity
if(condition)
getSupportFragmentManager().beginTransaction().replace(R.id.container,new FirstFragment()).commit();
else
getSupportFragmentManager().beginTransaction().replace(R.id.container, new SecondFragment()).commit();
if this not works try to get the fragment container view ID..Here's the code:
transaction.replace(((ViewGroup)(getView().getParent())).getId(), fragment);
It works for me...
int id = item.getItemId();
android.app.Fragment fragment = null;
if (id == R.id.nav_profile) {
fragment = new ProfileActivity();
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
}

calling a fragment from fragment

I want to call another fragment from the current fragment on the click of the button in the current fragment.
Here is my Mainactivity :
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
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 com.asd.fragments.RecommendationsFragment;
import com.asd.ibitz4college.fragments.SearchCoachingFragment;
import com.asd.fragments.SearchCollegesFragment;
import com.asd.fragments.MainFragment;
import com.asd.fragments.SearchConsultanciesFragment;
import com.asd.fragments.TrendingFragment;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).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();
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();
if (id == R.id.search_colleges) {
// Handle the Search Colleges action
fm.beginTransaction().replace(R.id.content_frame,new SearchCollegesFragment()).commit();
}
else if (id == R.id.search_consultancies) {
fm.beginTransaction().replace(R.id.content_frame,new SearchConsultanciesFragment()).commit();
}
else if (id == R.id.search_coaching) {
fm.beginTransaction().replace(R.id.content_frame,new SearchCoachingFragment()).commit();
}
else if (id == R.id.my_recommendations) {
fm.beginTransaction().replace(R.id.content_frame, new RecommendationsFragment()).commit();
}
else if (id == R.id.trending) {
fm.beginTransaction().replace(R.id.content_frame, new TrendingFragment()).commit();
} else if (id == R.id.profile) {
} else if (id == R.id.logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is one of my fragment :
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.asd.k4c.R;
public class SearchCoachingFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_search_coaching,container,false);
return rootview;
}
} //Update code formatting
Suppose I want to call resultsfragment from the above fragment on the click
of a button whose id is btn_search, then what should I do?
I tried some already existing answers here, no luck!
P.S: I'm a starter to the world of android dev.
For doing a fragment transaction.Please do the following.
Eg..
A and B are fragments.
Currently A is visible to the User. If you want to do a transaction.
Just create as like below
B b = new B();
((YourActivity)getActivity).setnewFragment(b,true);
public void setNewFragment(Fragment fragment,boolean addbackstack) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_content, fragment);
if (addbackstack)
transaction.addToBackStack(title);
transaction.commit();
}
Use an interface to communicate between fragments. For example
public YourFirstFragment extends Fragment {
public interface FragmentCallBack {
void callBack();
}
private FragmentCallBack fragmentCallBack;
public void setFragmentCallBack(FragmentCallBack fragmentCallBack) {
this.fragmentCallBack = fragmentCallBack;
}
private void callThisWhenYouWantToCallTheOtherFragment(){
fragmentCallBack.callBack();
}
}
Then in You activity
private void setCallToFragment{
yourFirstFragment.setFragmentCallBack(new FragmentCallBack(){
void callBack(){
yourSecondFragment.doWhatEver();
}})
}
First you need to create an interface which defines methods that will be used by your fragment to invoke code from the respective activity it is attached to
public interface OnFragmentInteractionlistener {
// the method that you call from your fragment,
// add whatever parameter you need in the implementation of this
// method.
void onClickOfMyView();
}
once you have created the interface, implement it any and all activities that use this fragment.
public class MainActivity extends AppCompatActivity
implements OnMyFragmentInteractionListener {
#Override
public void onClickOfMyView() {
// DO your on click logic here, like starting the transaction
// to add/replace another fragment.
}
}
Then in the onAttach of your fragment to an activity be sure to check if the attaching activity implements this interface, else throw a RunTimeException like so
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnMyFragmentInteractionListener) {
mListener = (OnMyFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnMyFragmentInteractionListener");
}
}
Here mListener is a interface reference you hold in your fragment class through which you invoke the onClickOfMyView() method when actually the click happens
Your fragment class where the view's click code is there.
myView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mListener.onClickOfMyview();
}
});
You should create some method in your activity. Supposedly it will look like this :
public void startFragment(Fragment fragment) {
fm.beginTransaction().replace(R.id.content_frame,new fragment).commit();
}
As you already done in youronNavigationItemSelected
Then, from your fragment, you can call
((MainActivity)getActivity()).startFragment(new SearchConsultanciesFragment())
for example
Create a method switchFragment in your MainActivity
FragmentTransaction ft;
public void switchFrag() {
try {
ft = getActivity().getFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, new Your_Fragment.class);
ft.commit();
} else {
Log.e("test", "else part fragment ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
Now from your current Fragment you can call this MainActivity's funciton throught the below code:
((MainActivity)getActivity()).switchFrag();
Let me know if this works for you! :)

Navigation Drawer fragment issue fragment to activity

Hi so i tried to make a Navigation drawer in a sample project which i use fragments and code works in "FRAGMENTS" but by the time i use the code in my THESIS project which i use "ACTIVITY" instead of fragments... the code wont work... i hope u help me with this here is the code
package org.intercode.triviaquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
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;
public class Navigation extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
//Set the fragment initially
//Set the fragment initially
Main fragment = new Main();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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.navigation, 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) {
Main fragment = new Main();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
Quiz fragment = new Quiz();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
and the red line comes from
fragment
Main fragment = new Main();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
in here to be exact
fragmentTransaction.replace(R.id.fragment_container, fragment);
the fragment after fragment_container has a redline... i believe the problem is because what i want to open when the app run is not a fragment the problem is i dont have idea what to replace it please help me guys its for my thesis :P

Opening a fragment(s) in home activity

I've been searching through Stack Overflow but couldn't seem to find something useful about this issue I am having ..
Below I have attached the code for the Home Activity that I have, and the XML file for it. I cant seem to get my head around what the problem is, I dunno what I am doing wrong. I want to show the content of a third class (e.g. the a different Fragment class for each of my fragments, basically I want to be able to show all the of the fragments in the same fragment holder in the home activity.. in this case I am trying to open the fragment Bookmarks (men.bookmarks)..
Any suggestions guys?
I didn't include the code for the fragment as it would be a lot of classes then, but If you need it, tell me :) ..
XML file for my HomeActivity:
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout
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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start" >
<include
layout="#layout/app_bar_home"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home"
app:menu="#menu/activity_home_drawer" />
<fragment
android:name="com.nooriandroid.n007.mybookmarks_v1.Fragment_Bookmarks"
android:id="#+id/fragBookmarks"
android:layout_weight="2"
android:layout_width="25dp"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
package com.nooriandroid.n007.mybookmarks_v1;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
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.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Activity_Home extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
//--------------Variables---------------------//
private String date_pattern = "hh:mm dd-MM-yyyy";
private Fragment fragment_bookmarks;
private Fragment_Favorite fragment_favorite;
private Fragment_Category fragment_category;
private Fragment_SharedWith_me fragment_sharedWith_me;
private Fragment_Myshared fragment_myshared;
private Activity_Home homeActivity;
private Fragment_Item_Container fragment_item_container;
private User user;
private boolean frag_favorite_visible = false, frag_bookmark_visible = false, frag_category_visible = false,
frag_myshared_visible = false, frag_sharedwithme__visible = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) 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 = (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);
//---------------Customized------------------//
setTitle("Home");
ActionBar ab = getSupportActionBar();
ab.setLogo(R.mipmap.ic_logolight);
ab.setDisplayUseLogoEnabled(true);
ab.setDisplayShowHomeEnabled(true);
fragment_favorite = new Fragment_Favorite();
fragment_bookmarks = new Fragment_Bookmarks();
fragment_category = new Fragment_Category();
fragment_myshared = new Fragment_Myshared();
fragment_sharedWith_me = new Fragment_SharedWith_me();
fragment_item_container = new Fragment_Item_Container();
homeActivity = this;
FragmentManager fragmentManager = getFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container, fragment_favorite);
fragmentTransaction.add(R.id.fragment_container, fragment_bookmarks);
fragmentTransaction.add(R.id.fragment_container, fragment_category);
fragmentTransaction.add(R.id.fragment_container, fragment_myshared);
fragmentTransaction.add(R.id.fragment_container, fragment_sharedWith_me);
frag_favorite_visible = true;
fragmentTransaction.hide(fragment_bookmarks);
fragmentTransaction.hide(fragment_category);
fragmentTransaction.hide(fragment_myshared);
fragmentTransaction.hide(fragment_sharedWith_me);
fragmentTransaction.commit();
goHomeOnclicked();
user = new User();
user = (User) getIntent().getSerializableExtra("currentuser");
}
#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.home, menu);
rundUserSettings();
SimpleDateFormat format = new SimpleDateFormat(date_pattern);
String current_date = format.format(new Date());
TextView nav_textview_Date = (TextView) findViewById(R.id.textView_Date);
nav_textview_Date.setText(current_date);
TextView nameLast_textView = (TextView) findViewById(R.id.textView_UsernameLastname);
nameLast_textView.setText("" + user.getName() + " " + user.getLast_name());
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.men_newItem) {
Intent intent_NewItem = new Intent("com.nooriandroid.n007.mybookmarks_v1.Activity_NewItem");
startActivity(intent_NewItem);
} else if (id == R.id.men_bookmarks) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
fragmentTransaction.show(fragment_bookmarks);
frag_bookmark_visible = true;
this.setTitle("Bookmarks"); ///Ombytnings Zirt
fragmentTransaction.commit(); ///
} else if (id == R.id.men_category) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_category_visible= true;
fragmentTransaction.show(fragment_category);
fragmentTransaction.commit();
this.setTitle("Categories ");
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
}
else if (id == R.id.men_share) {
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
} else if (id == R.id.men_sharedwithme) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_sharedwithme__visible = true;
fragmentTransaction.show(fragment_sharedWith_me);
fragmentTransaction.commit();
this.setTitle("Shared with me");
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
} else if (id == R.id.men_myshared) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_myshared_visible = true;
fragmentTransaction.show(fragment_myshared);
fragmentTransaction.commit();
this.setTitle("My shared");
Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void checkFragmentsStatus(FragmentTransaction fragmentTransaction){
if (frag_favorite_visible){
frag_favorite_visible = false;
fragmentTransaction.hide(fragment_favorite);
}else if (frag_bookmark_visible){
frag_bookmark_visible = false;
fragmentTransaction.hide(fragment_bookmarks);
}else if (frag_category_visible){
frag_category_visible = false;
fragmentTransaction.hide(fragment_category);
}else if (frag_myshared_visible){
frag_myshared_visible = false;
fragmentTransaction.hide(fragment_myshared);
}else if (frag_sharedwithme__visible){
frag_sharedwithme__visible = false;
fragmentTransaction.hide(fragment_sharedWith_me);
}
}
private void goHomeOnclicked(){
findViewById(R.id.toolbar).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!frag_favorite_visible){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
checkFragmentsStatus(fragmentTransaction);
frag_favorite_visible = true;
fragmentTransaction.show(fragment_favorite);
fragmentTransaction.commit();
homeActivity.setTitle("Home");
}
}
});
}
private boolean rundUserSettings(){
if (this.user!=null){
try {
File file = new File(user.getProfile_pic());
Uri uri = Uri.fromFile(file);
ImageView view = (ImageView) findViewById(R.id.imageView_ProfilePic);
view.setImageURI(uri);
}catch (Exception e){
Toast.makeText(Activity_Home.this,"Unable to load profile picture.!",Toast.LENGTH_SHORT).show();
}
return true;
} else {
return false;
}
}
}
The code you're using for adding different fragments on the same activity is really messed up. You can use better approach. I'm adding the sample code below:
In the layout of Activity, add this line of code
<FrameLayout
android:id="#+id/fragBookmarks"
android:layout_weight="2"
android:layout_width="25dp"
android:layout_height="match_parent" />
instead of:
<fragment
android:name="com.nooriandroid.n007.mybookmarks_v1.Fragment_Bookmarks"
android:id="#+id/fragBookmarks"
android:layout_weight="2"
android:layout_width="25dp"
android:layout_height="match_parent" />
Now write this method in your HomeActivity to add different fragments
public void addFragment(Fragment frag, String tag) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragBookmarks, frag, tag);
transaction.addToBackStack(getFragmentManager().getBackStackEntryCount() == 0 ? "FirstFragment" : null).commit();
}
}
This method will help you to add any fragment to this activity on the go. You don't need to add all the fragments from the beginning. Like If now I'm on HomeFragment and I want to open BookmarkFragment on button click from Home, I will write something like;
btnBookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity) getActivity()).addFragment(new BookmarkFragment(), BookmarkFragment.class.getSimpleName()); // This will add the new fragment Bookmark fragment to the activity while adding it to backstack
}
});
Now, If you want to go back from BookmarkFragment to HomeFragment, add this method in your HomeActivity
public void popFragment() {
if (getFragmentManager() == null)
return;
getFragmentManager().popBackStack();
}
And Call this function in BookmarkFragment like,
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((HomeActivity) getActivity()).popFragment(); // This will remove the last added fragment Bookmark fragment
}
});
DrawerLayout should have only two direct children.If you want to replace different fragments in same activity,create a FrameLayout in the app_bar_home layout.Then in your Activity,do this to replace fragments.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frame_layout_id,new yourFragment()).commit();

Categories

Resources