Cannot load Fragments from Navigation Drawer items - android

I have found a lot about this around but I really can't solve my problem. I have spent hours in this but nothing.
I have a Navigation Drawer Activity made with Android Studio 2.1.1 templates. Of course I want to change the view of my app, when I click on a item in the menu, showing different Fragments. This is the code that I have in the MainActivity:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
new gaussFragment();
} 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;
}
When I click on the first item of the navigation drawer (the one with the id R.id.nav_camera) I can see the toast but the new Fragment is not appearing. I am using this code in gaussFragment():
public class gaussFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_gauss, container, false);
}
}
Of course as you can see here the fragment_gauss.xml is its relative layout having this code:
<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"
tools:context="info.androidhive.tabsswipexx.gaussFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
How could I solve this?
The content_main is the first thing that I see when the app launches. Should I try to add something like
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
and somehow load there my fragments?

If you're using the Navigation Drawer template provided by Android Studio then in the navigation Drawer main activity xml you'll find something like :
<?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">
<!-- The main content view -->
<include layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- the navigation drawer the comes from the left-->
<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_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
If you take a closer look there you'll see that it consistst of two main parts that I have commented for you. One is for the navigation drawer stuff and the other is the main content wiew stuff. If you ctrl+click on layout="#layout/app_bar_main" you'll see that another xml opens which is the following:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="copsonic.com.SoundExchange.demoApp.MainActivity">
<!--Main View tool bar-->
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<!--The content that will be displayed in the main view when the navigation drawer is not opened-->
<include layout="#layout/content_main" />
<!--Floating Action Button Stuff-->
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:scaleType="center"
android:src="#mipmap/ic_rx_tx"
android:saveEnabled="false"
app:backgroundTint="#000000"
android:adjustViewBounds="false" />
</android.support.design.widget.CoordinatorLayout>
There you'll see 3 main parts, one for the tool bar, one for the Floating Action Button control and finally one for the content that will be displayed in the main view when the navigation drawer is not opened, this is the one you care about. If you ctrl+click in <include layout="#layout/content_main" /> You'll see a third xml were you must add a Fragmet container. In the end it's something like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/app_bar_main"
tools:context="copsonic.com.SoundExchange.demoApp.MainActivity">
<!-- A fragmet container to dynamically swap between fragmets-->
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
So after all this from your main activity code you just have to do two things, first manage which fragment is going to be seen first, you do this in the OnCreate method by adding :
FragmentTransmitter initialFragment = new FragmentTransmitter();
// Check that the activity is using the layout version with
// the fragment_container FrameLayout
if (findViewById(R.id.fragment_container) != null) {
// this check allows you not to load the default fragment unless
//it's the first time you launch the activity after having destroyed it
if (savedInstanceState != null) {
return;
}
// Create the fragment that is seen the first time your app opens
//pass useful info to the fragment from main activity if needed
//(it is recommended not to do this in the constructor, so you have to do it through a Bundle)
Bundle args = new Bundle();
args.putSerializable("ModulationType",aModulation);
initialFragment.setArguments(args);
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
//initialFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, initialFragment).commit();
}
And then the second thing is handle properly which fragment will be displayed each time an option is selected in the navigation drawer
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
FragmentTransmitter Gauss= new new gaussFragment();
//pass useful info to fragment if needed
Bundle args = new Bundle();
args.putSerializable(getString(R.string.ModulationType),aModulation);
Gauss.setArguments(args);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, Gauss,"TAG_GaussFragment"); //pacing a tag is not mandatory but it is pretty useful if you want to know later which fragment is being displayed in the fragment container
//transaction.addToBackStack(null);
transaction.commit();
} 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;
}

Related

Android setting DrawerLayout to the right issue

I'm trying to set the DrawerLayout to the right but i get this error:
java.lang.IllegalStateException: Child drawer has absolute gravity RIGHT but this
DrawerLayout already has a drawer view along that edge
Activity Code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_categories) {
//drawerLayout.openDrawer(GravityCompat.END);
if (drawerLayout.isDrawerOpen(Gravity.RIGHT))
drawerLayout.closeDrawer(Gravity.RIGHT);
else
drawerLayout.openDrawer(Gravity.RIGHT);
return true;
}
return super.onOptionsItemSelected(item);
}
layout
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/lightGrey"
android:id="#+id/drawer_layout"
tools:openDrawer="end"
tools:context=".MainActivity">
....
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/navigation_view"
android:layout_gravity="end"
app:menu="#menu/categories"/>
I tried multiple solutions from this question but none of them solved the problem. I tried using End instead of Right and GravityCompat instead of Gravity but always get this error.
The DrawerLayout can contain only 2 root layouts so I set the NavigationView and a LinearLayout that contains all other views and it's working now

After including Relative layout in the Drawer layout options in the menu don't respond to click

I created navigation drawer across multiple activities. In xml I have a Drawer layout. Before including relative (or others) layout in it, options in the menu were clickable (going to other activities). However, after including layout, it stopped going to other activities (options are not clickable).
<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"
android:clickable="true"
android:focusable="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main2"
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"
android:clickable="true"
android:focusable="true"
app:headerLayout="#layout/nav_header_main2"
app:menu="#menu/activity_main2_drawer" />
<include
layout="#layout/main2_image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
And code for Main2Activity:
#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.
//here is the main place where we need to work on.
int id=item.getItemId();
switch (id) {
case R.id.nav_camera:
Intent h = new Intent(Main2Activity.this, Main2Activity.class);
startActivity(h);
break;
case R.id.nav_gallery:
Intent g = new Intent(Main2Activity.this, Settings.class);
startActivity(g);
break;
case R.id.nav_slideshow:
Intent s = new Intent(Main2Activity.this, Allergy2.class);
startActivity(s);
break;
case R.id.nav_manage:
Intent t = new Intent(Main2Activity.this, Instruction.class);
startActivity(t);
break;
}
Why not using Fragments instead of Activities!!
To clear out your question you said that you want to switch between multiple activities and these all activities have the same NavigationDrawer Layout!
If yes its a very bad practice...you can use Fragments instead of each activity you've created in the NavDrawerMenu... TODO that follow me:
First you will create your MainActivity with the Navigation drawer as normal then in the method onNavigationItemSelected here you will begin the transactions between the fragments instead of Intent as follows:
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
//here is the main place where we need to work on.
int id=item.getItemId();
switch (id) {
case R.id.nav_camera:
getFragmentManager().beginTransaction()
.replace(R.id.main_frameLayout, new
BlankFragment1()).commit();
break;
case R.id.nav_gallery:
getFragmentManager().beginTransaction()
.replace(R.id.main_frameLayout, new
BlankFragment2()).commit();
break;
case R.id.nav_slideshow:
getFragmentManager().beginTransaction()
.replace(R.id.main_frameLayout, new
BlankFragment3()).commit();
break;
}
NOTE: you surly know that these fragments must be the child of an activity so main_frameLayout is the id of FrameLayout that the fragments are placed in in the activity you placed the NavigationDrawer in which is the MainActivity as follows:
app_bar_nav_drawer.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tkmsoft.taahel.activities.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="0dp"
android:layout_height="?android:actionBarSize"
android:theme="#style/AppTheme.AppBarOverlay"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.v7.widget.Toolbar
android:id="#+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent"
app:popupTheme="#style/AppTheme.PopupOverlay">
<TextView
android:id="#+id/toolbar_title"
style="#style/TextAppearance.Widget.AppCompat.Toolbar.Title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_toStartOf="#+id/toolbar_filter_button"
android:gravity="center|start"
android:textColor="#android:color/white" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/main_frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
What's probably happening here is that your drawer is shadowed by the additional children you've created in the DrawerLayout.
To fix this, in the onCreate method of your Main2Activity, get a reference to your NavigationView and bring it to front:
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.bringToFront();
If you added CoordinatorLayout and then inside -> AppBarLayout as it's child in app_bar_main2 with Toolbar, then you better to add your contents inside the CoordinatorLayout or maybe inside a NestedScrollView which is a child of the CoordinatorLayout.
The problem why they're not clickable is that the DrawerLayout cannot recognize this layout as it's child:
<include
layout="#layout/main2_image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
So, put the contents of this layout inside CoordinatorLayout and it's child NestedScrollView.

Navigation drawer and Bottom Bar navigation in same app

I'm trying to use navigation drawer and bottom bar nav in my app.therefore i have created navigation activity first.then i tried to add bottom bar nav to that same activity,like below.
inside onCreate
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
Activity.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
>
<include
layout="#layout/app_bar_main"
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_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
<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" />
</RelativeLayout>
without BottomNavigationView in Activity.xml,app is working.but when i add BottomNavigationView inside Activity.xml app crashed.nothing showing in logcat.
how can i use both bottombar nav and navigation drawer in same activity?
Open this layout
layout="#layout/app_bar_main"
and then in that layout add your bottom navigation view widget
<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" />
BottomNavigation and Navigation Drawer both uses OnNavigationItemSelectedListener to switch from one fragment to another.
Now, In your case you'll be having two menus
1-activity_home_drawer.xml
2-navigation.xml (Menu you created for BottomNavigation Bar)
So, you inside the method you'd have to write logic for both the menus.
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Navigation Drawer Menus below.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
selectedFragment = new Batteries();
bottomNavigationView.setVisibility(View.VISIBLE);
} else if (id == R.id.nav_gallery) {
selectedFragment = new Offers();
bottomNavigationView.setVisibility(View.INVISIBLE);
} 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) {
}
// Bottom Navigation Menus below
else if (id == R.id.navigation_dashboard){
selectedFragment = new Batteries();
}else if (id == R.id.navigation_home){
selectedFragment = new BatteryReport();
}else if (id == R.id.navigation_notifications){
selectedFragment = new ScanCode();
}
getSupportFragmentManager().beginTransaction()
.replace(R.id.frameLayout, selectedFragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

How to add a back button to action bar / toolbar

I have written a piece of code as part of an app where I want to implement a back button on the action bar/tool bar such that when the button is pressed, the previous page (the page/fragment immediately before the current page/fragment) will be displayed.
This is the code for the ToolBar, DrawerLayout, NavigationView and getSupportActionBar():
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setVisibility(View.VISIBLE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
I am unable to use ActionBar. For some reason (I don't know why), my Android studio/ program, will not allow me to use the ActionBar. So I am substituting that with the set/getSupportActionBar().
The function used in relation to this are:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_settings, 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();
switch (id) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
My activity_main.xml file is:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:id="#+id/activity_main"
android:orientation="vertical"
tools:openDrawer="start"
tools:context="com.example.albin.settings_menu.SettingsActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="Settings"/>
<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">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar">
</FrameLayout>
<android.support.design.widget.NavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:layout_marginTop="-24dp"
app:menu="#menu/options_menu" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
</LinearLayout>
The problem is that I don't know which is the useful code, which is the useless code and how to mix/join/(add additional codes to) these (codes, methods, variables/objects, fragments, xml layouts) to get the desired outcome, that is, the application of a back button on the action bar/tool bar.
Most of the code above is implemented for the up button, not the back button. I have read at several places that up and back buttons are not the same.
I tried several links on internet as well as on this site, but none of them has just what I need.
Hope someone can give me an clear answer...
You can include the back icon in ToolBar:
Initialize ToolBar:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
You can use an drawable icon as a back button.
toolbar.setNavigationIcon(R.drawable.your_drawable_icon);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// what do you want here
}
});
If you do not want to use drawable icon then:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// what do you want here
}
});
Actually your layout having that issue because you have added toolbar in RelativeLayout so drawer layout is overlapping on it that's why you would not able to click on back arrow, i have fix your layout see below
<?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"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:navigationIcon="#drawable/ic_back_black"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:title="Settings" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/frame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/options_menu" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
The simplest way would be to add parent activity in manifest file as developer docs suggest.
<activity
android:name=".ChildActivity"
android:parentActivityName=".ParentActivity" >
and java code you already have done it, setSupportActionbar and setHomeAsUpEnabled.
Edited :
its necessary to add up action for icon to be visible, as mentioned in
Android Developer Docs
So toolbar gives added flexibility to modify title-bar in Android.
As far as why getActionBar is not working and you are compelled to use getSupportActionBar is because you must be using SupportLibrary. SupportLibrary gives backward compatibility to earlier SDK versions.
If you want to modify your title-bar/header/action-bar extensively
then use toolbar otherwise use action-bar.
Add a navigation click listener to your toolbar , like below
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
If you are referencing some actions from the action bar, such as a Save action or a Share one, and you are overriding onOptionsItemSelected method, then you need to define the behavior when the back or home button is clicked:
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
//save stuff
break;
//this is what you need to add to reference again back/home button
case android.R.id.home:
//do your stuff here, usually back to the home or close the current activity
getActivity().finish();
break;
default:
break;
}
return true;

Android- FragmentTransaction.replace() works only once

I'm using a navigation drawer along with a SwipeRefreshLayout for the main content and when the user selects a menu item in the navigation drawer, I want to replace the fragment inside the SwipeRefreshLayout with another fragment.
This is what my onNavigationItemSelected() looks like:
// Handle navigation view item clicks here.
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
selectedNavItem = item.getItemId();
if(selectedNavItem == R.id.nav_files){
filesFragment = new FilesFragment();
fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.swipeLayout,filesFragment,"files");
transaction.commit();
} else if(selectedNavItem == R.id.nav_accounts){
accountsFragment = new AccountsFragment();
fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.swipeLayout,accountsFragment,"accounts");
transaction.commit();
}
return true;
But this never works. When I click an item in the nav drawer, the fragment is replaced by a blank screen. My onCreate method also uses FragmentTransaction.replace() but that seems to work fine.
I also tried FragmentTransaction.remove() and then FragmentTransaction.add() but even that doesn't seem to work.
Edit: Layout files:
Layout of the content view of the navigation drawer:
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.harshallele.cloudpool.MainActivity"
tools:showIn="#layout/app_bar_main"
android:id="#+id/swipeLayout">
</android.support.v4.widget.SwipeRefreshLayout>
This is included inside another layout file which contains a CoordinatorLayout containing the toolbar.That file, in turn, is inside the main layout file of the activity inside a android.support.v4.widget.DrawerLayout
(Basically, this is the Navigation Drawer Activity provided by Android Studio when adding an Activity)
Layout for FilesFragment:
<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"
tools:context=".fragments.FilesFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/fileListView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
/>
<ProgressBar
android:id="#+id/itemsLoadingProgress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
style="?android:attr/progressBarStyleHorizontal"
android:indeterminateOnly="true"
android:visibility="invisible"
/>
</FrameLayout>
Layout for AccountsFragment(this is just the default blank fragment, because i haven't finished this yet):
<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"
tools:context="com.harshallele.cloudpool.fragments.AccountsFragment">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
Edit 2:
AccountsFragment:
public class AccountsFragment extends Fragment {
public AccountsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_accounts, container, false);
}
}
With just this bit of code we can't help you so much. The problem can be that:
The FilesFragment and AccountsFragment aren't initialized in the right way;
The Layout with id swipeLayout can have visibility = gone;
The Layout of FilesFragment and AccountsFragment can be empty;
This are just some of the infinite reason why your code doesn't work properly so please share more code about the two Fragments and relative XML.

Categories

Resources