I want to implement onBackPress to my fragment but i don't know how. When i go to another fragment (in this case, my fragment is the one from my ActivityHome and i'm using standard NavigationDrawer from android stuudio).
Here is my code for ActivityHome
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
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 fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentHome fragment = new FragmentHome();
fragmentTransaction.add(R.id.containerID, fragment);
fragmentTransaction.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.activity_home, 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_logout) {
Toast.makeText(getApplicationContext(),
"Akun anda telah dikeluarkan!", Toast.LENGTH_LONG).show();
Intent logout = new Intent(ActivityHome.this, ActivityMain.class);
startActivity(logout);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.nav_home){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, FragmentHome.newInstance()).commit();
}else if (id == R.id.nav_profile){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, Profile.newInstance()).commit();
}
else if (id == R.id.nav_history){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, History.newInstance()).commit();
}
else if (id == R.id.nav_about_us){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, AboutUs.newInstance()).commit();
}
else if (id == R.id.nav_ganti_kata_sandi){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, GantiKataSandi.newInstance()).commit();
}
else if (id == R.id.nav_share){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, Share.newInstance()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
I hope u guys can help me with my problem.
I have webview in fragment, I used this code to detect backpress code in mainactivity OnbackPressed():
Fragment webview = getSupportFragmentManager().findFragmentByTag("BLOG");
if (webview instanceof BlogFragment) {
boolean goback = ((BlogFragment) webview).canGoBack();
if (!goback) {
} else {
((BlogFragment) webview).goBack();
}
}
Make sure you start fragment like:
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.frame_content, new BlogFragment(), "BLOG")
.commit();
To open fragment from activity.
Fragment fragment = Fragment.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fragment_slide_left_enter,
R.anim.fragment_slide_left_exit, R.anim.fragment_slide_right_enter,
R.anim.fragment_slide_right_exit);
addFragmentToActivity(fragmentTransaction, Fragment, R.id
.content_frame);
public void addFragmentToActivity(#NonNull FragmentTransaction transaction,
#NonNull Fragment fragment, int frameId) {
transaction.addToBackStack(fragment.getClass().getName());
transaction.add(frameId, fragment, fragment.getClass().getName());
transaction.commit();
}
That's how I add fragment from HomeActivity and For back Call override method OnBackPressed in HomeActivity.
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
getSupportFragmentManager().popBackStackImmediate();
}
You can get event when back button pressed from any fragment in Activity's onBackPressed() method.
Suppose you've pressed back from HomeFragment then you can get onBackPressed in Activity like following :
#Override
public void onBackPressed() {
HomeFragment fragment = (Fragment)findFragmentById(// fragment id);
if(fragment!=null && fragment.isVisible()){
// Here you can code for Home Fragment's onBackPress()
}
super.onBackPressed();
}
Related
I am getting Problem in Navigation drawer if I am clicking any drawer item more than one time (Example 5 times) then on back press I am getting 5 time same fragment.
Suppose first I had click on Fragment one then 5 times on fragment two then after on Back Handling or on Back Pressed first 5 times second fragment has been called and the the fragment one.
I want that if the same no. of fragment I have clicked multiple times the no need to push it on stack.
How to handle this?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,HomeListFragment.MyListFragmentListener {
private Stack<Fragment> fragmentStack;
private FragmentManager fragmentManager;
private HomeListFragment homeListFragment;
private ResultListFragment resultListFragment;
#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);
fragmentStack = new Stack<Fragment>();
homeListFragment = new HomeListFragment();
homeListFragment.registerForListener(this);
fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(R.id.container, homeListFragment);
fragmentStack.push(homeListFragment);
ft.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (fragmentStack.size() >1) {
FragmentTransaction ft = fragmentManager.beginTransaction();
fragmentStack.lastElement().onPause();
ft.remove(fragmentStack.pop());
fragmentStack.lastElement().onResume();
ft.show(fragmentStack.lastElement());
ft.commit();
} 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);
}
#Override
public void onItemClickedListener(String valueClicked) {
Toast.makeText(this, valueClicked, Toast.LENGTH_LONG).show();
FragmentTransaction ft = fragmentManager.beginTransaction();
resultListFragment = new ResultListFragment();
ft.add(R.id.container, resultListFragment);
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(resultListFragment);
ft.commit();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
FragmentTransaction ft = fragmentManager.beginTransaction();
One one = new One();
ft.replace(R.id.container, one,"One");
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(one);
ft.commit();
} else if (id == R.id.nav_gallery) {
FragmentTransaction ft = fragmentManager.beginTransaction();
Two two = new Two();
ft.replace(R.id.container, two,"Two");
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(two);
ft.commit();
} else if (id == R.id.nav_slideshow) {
FragmentTransaction ft = fragmentManager.beginTransaction();
Three three = new Three();
ft.replace(R.id.container, three,"Three");
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(three);
ft.commit();
} else if (id == R.id.nav_manage) {
FragmentTransaction ft = fragmentManager.beginTransaction();
Four four = new Four();
ft.replace(R.id.container, four,"Four");
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(four);
ft.commit();
} 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;
}
Please Help
//You are using backstack to hold the previous fragments remove all the fragment stacks
One one = new One();
ft.replace(R.id.container, one,"One");
ft.commit();
or you may use below code in backPress method
getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
You can simply check the current fragment instance is exist or not by tag. Check the fragment is exist or not and then do your logic by that.
Fragment fragment = getFragmentManager().findFragmentByTag("yourstringtag");
if (fragment instanceof yourFragment) {
// No need to commit new one
} else {
// Commit new one
}
Another simple method to solve this issue by using a currentFragment instance. Please consider this as an example logic, I didn't checked it.
private Fragment mFragment;
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
if (!(mFragment instanceof One)) {
FragmentTransaction ft = fragmentManager.beginTransaction();
One one = new One();
ft.replace(R.id.container, one, "One");
fragmentStack.lastElement().onPause();
ft.hide(fragmentStack.lastElement());
fragmentStack.push(one);
mFragment = one;
ft.commit();
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
I have a navigation drawer activity with fragments within it by using a fragment container. I have three fragments within it and I need one of it named locate_login to not contain my navigation drawer.
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); //nav drawer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
locate_login fragment = new locate_login();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
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){ //ignore this
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) {
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is my locate_login fragment
public class locate_login extends Fragment{
public locate_login () {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.locate_login, container, false);
// Inflate the layout for this fragment
return rootView;
}
}
I will highly appreciate it if the answer will be detailed since I'm a beginner on Android Studio.
Create a class for some constant parameter. Declare some constant variable like:
Let say StringConstant.java :
public static final int LOCK_DRAWER = 1;
public static final int SHOW_DRAWER = 2;
When navigating from the drawer, use an Intent object as:
If you want to show the drawer, use:
intent.putExtra("SHOW_DRAWER", StringConstant.SHOW_DRAWER);
OR
If you do not want to show the drawer, use:
intent.putExtra("SHOW_DRAWER", StringConstant.LOCK_DRAWER);
Retrieve intent from your fragment class, you say locate_login.
int status = getActivity.getIntent().getIntExtra("SHOW_DRAWER", 0);
Check status:
if (status == String.Constant.LOCK_DRAWER){
lockDrawer();
}
public void lockDrawer() {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
To unlock the drawer:
public void unlockDrawer() {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
Thank you for spending time on my qeustion. In my app I am using android studio navigation drawer template.
But the problem is that, when I rotate the phone, the previous fragment's layout is shown above the current fragment.
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);
Fragment fragment = null;
Class fragmentClass = null;
/* if (savedInstanceState == null){
try{
fragment = (Fragment) fragmentClass.newInstance();
}catch (Exception e){
e.printStackTrace();
}
}*/
fragment = new Login();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment, fragment);
fragmentTransaction.commit();
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();
Fragment fragment =null ;
Class fragmentClas = null;
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new Attendance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
fragment = new AddStudent();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment, fragment);
fragmentTransaction.commit();
} 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) {
}
/* FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();*/
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
When you rotate the device, the activity saves its current state and keeps the current fragment then it's destroyed and recreated i.e. onCreate() is called again. You had one fragment before it's destroyed and now it added another in the new call to onCreate() that's why you have 2 fragments. To fix this you should check first if the savedInstanceState parameter in onCreate() is null i.e. it's the first creation of activity not just being restarted due to rotation change or anything, then decide to add the fragment or not instead of adding to whenever the activity calls onCreate()
if(savedInstanceState == null) {
// Add the fragment because it's normal creation
fragment = new Login();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment, fragment);
fragmentTransaction.commit();
}
Here i want to add a home and exit method. When i will press exit option, the app will close (with the R.id.exit) and when i pressed home button, user will come to the home screen (with the R.id.homepage). Here is my code:
#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 = getFragmentManager();
if (id == R.id.homepage) {
} else if (id == R.id.foodpage) {
//handle the food page here
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
} else if (id == R.id.schedulepage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ScheduleFragment())
.commit();
} else if (id == R.id.emotionspage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new EmotionsFragment())
.commit();
} else if (id == R.id.basicneedspage) {
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new BasicneedsFragment())
.commit();
} else if (id == R.id.exit) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
You can do it like this
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getFragmentManager();
switch(id){
case R.id.home:
//If you are in the same Activity
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new YourHomeFragment())
.commit();
//If you are in other activity and you call from fragment home page , just make intent to your Activity which holds home page
Intent intent = new Intent(getActivity(),YourActivityWhichHoldHomePage.class);
startActivity(intent);
break;
case R.id.foodpage:
//handle the food page here
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new FirstFragment())
.commit();
break;
case R.id.schedulepage:
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new ScheduleFragment())
.commit();
break;
case R.id.emotionspage:
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new EmotionsFragment())
.commit();
break;
case R.id.basicneedspage:
fragmentManager.beginTransaction()
.replace(R.id.content_frame
, new BasicneedsFragment())
.commit();
break;
case R.id.exit:
//if you are in your activity close your app with
finish();
//or if you are insome fragment use
getActivity().finish();
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
I do it with switch case because is more clearly to read it, my opinion, but you can do with if else of course!
Hope to help!
I have made navigation drawer in Android Studio.
Right now each fragment from drawer is leading to nowhere.
I need to know how can I switch between fragments and click on each one
I know i need to make new fragment, but what method to use so I can click on Settings from navigation drawer so it lead me to fragment Share?
Here is my code;
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();
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;
}
}
You are in the right direction. Just add the Fragment class in each of the Navigation items like below
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new DefaultFragment();
fragmentManager.beginTransaction().replace(R.id.first_container, fragment).commit();
} else if (id == R.id.nav_gallery) {
fragment = new ItemListFragment();
fragmentManager.beginTransaction().replace(R.id.first_container, fragment).commit();
}
}
at the end of onCreate(Bundle savedInstanceState)method, you can set the default Fragment to open on Activity load.
FragmentManager fragmentManager = getSupportFragmentManager();
DefaultFragment fragment = new DefaultFragment();
fragmentManager.beginTransaction().replace(R.id.first_container, fragment).commit();
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.`enter code here`
int id = item.getItemId();
FragmentManager fragmentManager =getSupportFragmentManager();
GoogleMap googleMap =getSupportFragmentManager();
if (id == R.id.alarme){
} else if (id == R.id.map) {
fragmentManager.beginTransaction().replace(R.id.contenedor,new mapposta()).commit();
} else if (id == R.id.parametre) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;