drawerLayout overlapping fragments - android

I have been at this problem for a while
I believe its because something is not correct with the drawerLayout implementation, even tho I followed the developer site to implement it.
I have an activity, that for now has 3 frames, mangaSearch(mS)(recyclerView), profile, settings
mS is the start fragment, when i go to the drawer menu and select profile or settings, the fragments are drawn above the mS fragment. when i hit back the mS fragment is shown normal again, as intended.
I have looked around on google/stack but have not found a solution for this problem, hence I am asking here for help.
Update
I had the wrong id's in drawer, i had to change them in to the ones from the navigation nav_graph layout.
mainActivity
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.material.navigation.NavigationView;
import Classes.LoggedInUser;
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawer;
private AppBarConfiguration appBarConfig;
public static LoggedInUser loggedInUser;
FragmentManager fm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loggedInUser = LoggedInUser.getInstance();
fm = getSupportFragmentManager();
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
appBarConfig = new AppBarConfiguration.Builder(R.id.nav_graph_manga_book_details,
R.id.nav_graph_mangas_search_souce, R.id.nav_graph_profile,
R.id.nav_graph_settings).setDrawerLayout(drawer).build();
NavController navController = Navigation.findNavController(this, R.id.main_content);
NavigationView navigationView = findViewById(R.id.nav_view);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfig);
//NavigationUI.setupWithNavController(navigationView, navController);
DrawerLayout drawerL = findViewById(R.id.drawer_layout);
NavigationUI.setupActionBarWithNavController(this, navController, drawerL);
NavigationUI.setupWithNavController(navigationView, navController);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_manga_books_source:
fm.beginTransaction().replace(R.id.main_content, new MangasSearchFragment(), "mangaBookSource").commit();
break;
case R.id.nav_user_profile:
//check if person is logged in?
fm.beginTransaction().replace(R.id.main_content, new ProfileFragment(), "profile").commit();
break;
case R.id.nav_settings:
fm.beginTransaction().replace(R.id.main_content, new SettingsFragment(), "settings").commit();
break;
case R.id.nav_settings_temp:
Toast.makeText(MainActivity.this, "Settings Temp works", Toast.LENGTH_SHORT).show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.main_content);
return NavigationUI.navigateUp(navController, appBarConfig) || super.onSupportNavigateUp();
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
}
The layout file
<androidx.drawerlayout.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:orientation="vertical"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/main_content"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="#navigation/navigation_graph"
app:defaultNavHost="true"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
layout drawer_menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_user_profile"
android:icon="#drawable/ic_user_profile"
android:title="Profile" />
<item
android:id="#+id/nav_manga_books_source"
android:icon="#drawable/ic_manga_books_of_source"
android:title="Manga's"/>
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_settings"
android:title="Settings"/>
</group>
<item android:title="new group">
<menu>
<item
android:id="#+id/nav_settings_temp"
android:icon="#drawable/ic_settings"
android:title="Settings temp" />
</menu>
</item>
</menu>
the later added navigation component recommended by someone. The problem was there already and this did not fix it, as it was not intended as a fix, but it might be relevant to the mainActivity code
<?xml version="1.0" encoding="utf-8"?>
<navigation 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/mobile_navigation"
app:startDestination="#+id/nav_graph_mangas_search_souce">
<fragment
android:id="#+id/nav_graph_mangas_search_souce"
android:name="com.example.what2watchmangareader.MangasSearchFragment"
android:label="start fragment"
tools:layout="#layout/fragment_mangas_to_search" />
<fragment
android:id="#+id/nav_graph_profile"
android:name="com.example.what2watchmangareader.ProfileFragment"
android:label="profile page"
tools:layout="#layout/fragment_profile" />
<fragment
android:id="#+id/nav_graph_settings"
android:name="com.example.what2watchmangareader.SettingsFragment"
android:label="Settings Page"
tools:layout="#layout/fragment_settings" />
<fragment
android:id="#+id/nav_graph_manga_book_details"
android:name="com.example.what2watchmangareader.MangaBookFragment"
android:label="Manga detail"
tools:layout="#layout/fragment_manga_book_info" />
//Add your other fragments here.
</navigation>

As per the documentation, you don't need to run any FragmentTransactions nor do you need to manually implement a OnNavigationItemSelectedListener when using setupWithNavController(). Instead, you only need to match the android:id between your navigation graph and menu items.

Related

Navigation menu and add button on selective fragments in android

I need your help to understand the concept of menu in android.
I am using a navigation menu(bar) in android and load it on the MainActivity and put three different fragments.
On app start the navigation menu opened and default fragment also loaded as mentioned below.
Here everything is ok, but when i click on the third menu option (Credit Cards) then a fragment opened in that fragment, i am using ListView as mentioned below:
Now i want the add button on the bar, here you can see its below the bar.
How i can achive this? please help me out. Here i want the burger icon for navigation at left side and add icon/button at right side on same bar.
Note: I tried to add the button on the toolbar i am using inside the DrawerLayout but this button appears on all the fragments.
Here is the code for activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.ac 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=".MainActivity"
android:id="#+id/drawer_layout"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:id="#+id/toolbar"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
>
</android.support.v7.widget.Toolbar>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/fragement_container"/>
</LinearLayout>
<android.support.design.widget.NavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu" >
</android.support.design.widget.NavigationView>
</android.support.v4.widget.ac>
MainActivity.java
package com.mas.mas;
import android.os.Bundle;
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.MenuItem;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.nagivation_drawer_open, R.string.nagivation_drawer_close);
drawerLayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new TransactionsListFragment()).commit();
setTitle("Transactions");
navigationView.setCheckedItem(R.id.transactions);
}
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.transactions:
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new TransactionsListFragment()).commit();
setTitle("Email");
break;
case R.id.banks:
// getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new MessageFragement()).commit();
setTitle("Banks");
break;
case R.id.cards:
setTitle("Cards");
getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new CardsFragment()).commit();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
Thanks.
Add button in tool bar in mainActivity
<androidx.appcompat.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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/adimage"
android:layout_marginBottom="#dimen/padd_10"
android:layout_marginTop="#dimen/padd_10"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ad"></ImageView>
</RelativeLayout>
then use this for onClick Listner In mainActivity.java
Toolbar toolbar = findViewById(R.id.toolbar);
adsImageView=toolbar.findViewById(R.id.adimage);
adsImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
hope it helps

How can I implement my custom toolbar in my Fragment

I read so much article and watched so many videos but I still don't know, how to set up an action bar in an Fragment. I have a activity X with an custom toolbar and one navigation view on the top left(the toolbar is separated in an xml file), I import it in the xml for the activity X.
Here is my toolbar in one single xml:
<?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/drawerChooser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/new_gradients"
android:fitsSystemWindows="true"
tools:context=".ChoosingActivity">
<!--tools:openDrawer="start"-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</LinearLayout>
<FrameLayout
android:id="#+id/fragment_container_toolbar"
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"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
EDIT, new toolbar:
<LinearLayout 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"
xmlns:tools="http://schemas.android.com/tools"
android:background="#drawable/new_gradients"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/new_gradients"
android:fitsSystemWindows="true"
tools:context=".ChoosingActivity">
<FrameLayout
android:id="#+id/fragment_container_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu">
</android.support.design.widget.NavigationView>
</LinearLayout>
</LinearLayout>
Here is my activity X:
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.support.annotation.NonNull;
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.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class ChoosingActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
public void userChoosed(View view) {
Intent choosedIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(choosedIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choosing);
Toolbar toolbar = findViewById(R.id.toolbarxml);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawerChooser);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Item will be Selected
switch (item.getItemId()) {
case R.id.nav_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Ausstehende_Treffen_Fragment()).commit();
break;
case R.id.nav_finished_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Abgeschlossene_Treffen_Fragment()).commit();
break;
case R.id.nav_rate:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Treffen_Bewerten_Fragment()).commit();
break;
case R.id.nav_edit_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Profil_Bearbeiten_Fragment()).commit();
break;
case R.id.nav_settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Einstellungen_Fragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
EDIT, new activity X ( look at my comment "Toolbar_chooser or toolbar"):
public class ChoosingActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
public void userChoosed(View view) {
Intent choosedIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(choosedIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choosing);
Toolbar toolbar = findViewById(R.id.toolbar_chooser); // Toolbar_chooser or toolbar?
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawerChooser);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
// Item will be Selected
switch (item.getItemId()) {
case R.id.nav_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Ausstehende_Treffen_Fragment()).commit();
break;
case R.id.nav_finished_meetings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Abgeschlossene_Treffen_Fragment()).commit();
break;
case R.id.nav_rate:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Treffen_Bewerten_Fragment()).commit();
break;
case R.id.nav_edit_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Profil_Bearbeiten_Fragment()).commit();
break;
case R.id.nav_settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_toolbar, new Einstellungen_Fragment()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
And here my Fragment where I want to add the toolbar with the navigation view:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
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.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class Ausstehende_Treffen_Fragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_ausstehende_treffen,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).getSupportActionBar(toolbar); // HOW???
}
}
EDIT, new Fragment:
public class Ausstehende_Treffen_Fragment extends Fragment {
// Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbarreal);
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_ausstehende_treffen,container,false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Toolbar toolbar = ((ChoosingActivity)getActivity()).findViewById(R.id.toolbar_ausstehende_treffen);
}
}
Here is also my xml for the fragment, where I want to have the toolbar:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_orange_light">
<include
android:id="#+id/toolbar_ausstehende_treffen"
layout= "#layout/toolbar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ausstehende Treffen Fragment"
android:textSize="25sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
Im not able anymore to open my navigation bar in my choosing activity and I don't know why..
I include the toolbars manually in the xml files, its necessary right? + some code in the fragment itself. Man I hope you understand my code and my problems. Pls help me I just want to keep my custom toolbar in any fragment and activity.
Pls help me, its so frustrating, waste so many hours for just a toolbar, which already exists..
Try adding toolbar in you activity :
mTopToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(mTopToolbar);
Get the Activity that owns the fragment (Fragment.getActivity()) and set its ActionBar property.
Then juse use the same setDisplayHomeAsUpEnabled method you mentioned to begin with on the ActionBar after setting your toolbar as the ActionBar to get the back / up button.
sample to access it from fragment :
((AppCompatActivity)getActivity()).getSupportActionBar().setSubtitle();
Hope it helps.
As simple as this.
Toolbar toolbar = ((ChoosingActivity)getActivity()).findViewById(R.id.toolbar);
Now do whatever you want to do man ;).
It's probably because your Toolbar is covered by everything else in DrawerLayout. Try swapping LinearLayout and DrawerLayout, so that the vertical LinearLayout is your root layout, something like this:
<LinearLayout 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"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerChooser"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/new_gradients"
android:fitsSystemWindows="true"
tools:context=".ChoosingActivity">
<FrameLayout
android:id="#+id/fragment_container_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.DrawerLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer_menu">
</android.support.design.widget.NavigationView>
</LinearLayout>
Something approximately like that, the key is that your Toolbar has to be outside your DrawerLayout.

when adding navigation drawer to the application. this does not work

Since a few days ago I decided to program for Android and buy a book about that. There are several examples and I have achieved them satisfactorily but at the moment of programming the navigation drawer and running it on my cell phone it appears that it closed unfortunately. In the console of Android Studio does not appear any error and I was reviewing codes, example, etc and I have not been able to solve the problem.
Here you can see part of the application code to create and initialize the toolbar and the drawer layout
package com.example.luisenrique.clase_aplicacion;
import android.content.SharedPreferences;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
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.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.example.luisenrique.clase_aplicacion.fragments.DetalleFragment;
import com.example.luisenrique.clase_aplicacion.fragments.SelectorFragment;
import static android.R.id.toggle;
import static com.example.luisenrique.clase_aplicacion.R.id.appBarLayout;
import static com.example.luisenrique.clase_aplicacion.R.id.drawer_layout;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private AdaptadorLibrosFiltro adaptador;
private AppBarLayout appBarLayout;
private TabLayout tabs;
private DrawerLayout drawer;
private ActionBarDrawerToggle toggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if((findViewById(R.id.contenedor_pequeno)!=null) && (getSupportFragmentManager().findFragmentById(R.id.contenedor_pequeno)==null)){
SelectorFragment primerFragment=new SelectorFragment();
getSupportFragmentManager().beginTransaction().add(R.id.contenedor_pequeno,primerFragment).commit();
}
adaptador=((Aplicacion)getApplicationContext()).getAdaptador();
appBarLayout=(AppBarLayout)findViewById(R.id.appBarLayout);
//Pestañas
TabLayout tabs=(TabLayout)findViewById(R.id.tabs);
tabs.addTab(tabs.newTab().setText("Todos"));
tabs.addTab(tabs.newTab().setText("Nuevos"));
tabs.addTab(tabs.newTab().setText("Leidos"));
tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
tabs.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener(){
#Override
public void onTabSelected(TabLayout.Tab tab){
switch (tab.getPosition()){
case 0: //Todos
adaptador.setNovedad(false);
adaptador.setLeido(false);
break;
case 1: //Nuevos
adaptador.setNovedad(true);
adaptador.setLeido(false);
break;
case 2: //Leidos
adaptador.setNovedad(false);
adaptador.setLeido(true);
break;
}
adaptador.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab){}
#Override
public void onTabReselected(TabLayout.Tab tab){}
});
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.drawer_open,R.string.drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView=(NavigationView)findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item){
int id=item.getItemId();
if(id==R.id.nav_todos){
adaptador.setGenero("");
adaptador.notifyDataSetChanged();
}
else if(id==R.id.nav_epico){
adaptador.setGenero(Libro.G_EPICO);
adaptador.notifyDataSetChanged();
}
else if(id==R.id.nav_XIX){
adaptador.setGenero(Libro.G_S_XIX);
adaptador.notifyDataSetChanged();
}
else if(id==R.id.nav_suspense){
adaptador.setGenero(Libro.G_SUSPENSE);
adaptador.notifyDataSetChanged();
}
DrawerLayout drawer=(DrawerLayout)findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed(){
DrawerLayout drawer=(DrawerLayout)findViewById(R.id.drawer_layout);
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
}
<!--activity main.xml-->
the main activity is where the main view will be shown and it will be linked to app_bar_main_xml where the other components are located that have no relation to the navigation drawer and work correctly and therefore I will not put the code.
<?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"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!--El contenido de la actividad-->
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!--El contenido del navigation drawer-->
<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>
<!--nav header-->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="160dp"
android:background="#color/colorAccent"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="?attr/listPreferredItemPaddingLeft"
android:paddingRight="?attr/listPreferredItemPaddingRight"
android:paddingTop="16dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="16dp"
android:src="#android:drawable/sym_def_app_icon"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="16dp"
android:text="Audiolibros"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="http://www.androidcurso.com"/>
</LinearLayout>
<!--menu activity_main_drawer.xml-->
in the menu you will see how the navigation drawer will be sectioned. what items will be available and how they will be grouped.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item android:id="#+id/nav_todos"
android:icon="#android:drawable/ic_menu_gallery"
android:title="Todos los generos"/>
<item android:id="#+id/nav_epico"
android:icon="#android:drawable/ic_menu_gallery"
android:title="Poema épico"/>
<item android:id="#+id/nav_XIX"
android:icon="#android:drawable/ic_menu_gallery"
android:title="Literatura siglo XIX"/>
<item android:id="#+id/nav_suspense"
android:icon="#android:drawable/ic_menu_gallery"
android:title="Suspense"/>
</group>
<item android:title="Acciones adicionales">
<menu>
<item android:id="#+id/nav_preferencias"
android:icon="#android:drawable/ic_menu_manage"
android:title="Preferencias"/>
<item android:id="#+id/nav_compartir"
android:icon="#android:drawable/ic_menu_share"
android:title="Compartir"/>
</menu>
</item>
</menu>
It is to call the texts that are required in other classes, there are only two that are called opening and closing.
<!--Strings-->
<resources>
<string name="app_name">Clase_Aplicacion</string>
<string name="drawer_open">navigation drawer abierto</string>
<string name="drawer_close">navigation drawer cerrado</string>
</resources>

ObservableScrollView hamburger icon missing

I have an activity with frame layout. When the options are clicked from the navigation drawer, it opens the specific fragment. I was trying to implement observablescrollview in my fragment. https://github.com/ksoichiro/Android-ObservableScrollView. I am able to implement it but I am not getting the hamburger icon in the actionbar. I realized it has to be bundled with the drawertoggle but that resides in my mainactivity. How do i get it in my fragment? Users may not even realize the presence of a navigation drawer without it. It was available when I was using a toolbar in app_bar_main.xml. I hope I have made myself clear. Please let me know if you require any other information. Help a newbie out. Thanks in advance.
Here's the screenshots.
Here's my code
activity_main.xml
<?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_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>
app_bar_main.xml
<?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="net.simplifiedcoding.navigationdrawerexample.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="net.simplifiedcoding.navigationdrawerexample.MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
fragment_menu_1.xml
<FrameLayout 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">
<com.github.ksoichiro.android.observablescrollview.ObservableScrollView
android:id="#+id/scroll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="#dimen/parallax_image_height"
android:scaleType="centerCrop"
android:src="#drawable/example" />
<View
android:id="#+id/anchor"
android:layout_width="match_parent"
android:layout_height="#dimen/parallax_image_height"
android:minHeight="#dimen/parallax_image_height" />
<TextView
android:id="#+id/body"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/anchor"
android:background="#android:color/white"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:text="#string/lipsum" />
</RelativeLayout>
</com.github.ksoichiro.android.observablescrollview.ObservableScrollView>
<include layout="#layout/gradient_header" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:popupTheme="#style/Theme.AppCompat.Light.DarkActionBar"
app:theme="#style/Toolbar" />
</FrameLayout>
Menu1.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.github.ksoichiro.android.observablescrollview.ScrollUtils;
import com.nineoldandroids.view.ViewHelper;
public class Menu1 extends Fragment implements ObservableScrollViewCallbacks {
private View mImageView;
private View mToolbarView;
private ObservableScrollView mScrollView;
private int mParallaxImageHeight;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
View v = inflater.inflate(R.layout.fragment_menu_1, container, false);
((AppCompatActivity)getActivity()).setSupportActionBar((Toolbar)v.findViewById(R.id.toolbar));
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
mImageView = v.findViewById(R.id.image);
mToolbarView = v.findViewById(R.id.toolbar);
mToolbarView.setBackgroundColor(ScrollUtils.getColorWithAlpha(0, getResources().getColor(R.color.primary)));
mScrollView = (ObservableScrollView) v.findViewById(R.id.scroll);
mScrollView.setScrollViewCallbacks(this);
mParallaxImageHeight = getResources().getDimensionPixelSize(R.dimen.parallax_image_height);
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Menu 1");
}
#Override
public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
int baseColor = getResources().getColor(R.color.primary);
float alpha = Math.min(1, (float) scrollY / mParallaxImageHeight);
mToolbarView.setBackgroundColor(ScrollUtils.getColorWithAlpha(alpha, baseColor));
ViewHelper.setTranslationY(mImageView, scrollY / 2);
}
#Override
public void onDownMotionEvent() {
}
#Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
}
}
MainActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
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 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);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
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);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_menu1);
}
#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);
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_menu1:
fragment = new Menu1();
break;
case R.id.nav_menu2:
fragment = new Menu2();
break;
case R.id.nav_menu3:
fragment = new Menu3();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}
}
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="Toolbar" parent="Theme.AppCompat">
<item name="colorPrimary">#color/primary</item>
<item name="colorPrimaryDark">#color/primaryDark</item>
<item name="colorAccent">#color/accent</item>
</style>
</resources>
On your MainActivity#onCreate, before calling toggle.syncState(), call toggle.setDrawerIndicatorEnabled(true)
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.setDrawerIndicatorEnabled(true)
toggle.syncState();

Fragment is not getting displayed on clicking the menu item in Navigation Drawer

I have a Navigation Drawer in which I have plenty of Menu Items. I have made a fragment "Home" and then on clicking on the Home menu item the Home Fragment should open.But it's not opening.
My java code is:
package com.example.hsports.weddingplanner.Activities;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import com.example.hsports.weddingplanner.Fragments.Home;
import com.example.hsports.weddingplanner.R;
public class FrontPage extends AppCompatActivity {
NavigationView navigationView;
DrawerLayout drawer;
Toolbar toolbar;
String nameOnTitleBar[];
int indexSelected=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_front_page);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer=(DrawerLayout)findViewById(R.id.drawer_layout);
navigationView=(NavigationView)findViewById(R.id.nav_view);
nameOnTitleBar=getResources().getStringArray(R.array.nav_list_items);
setupNavigationView();
}
private void setupNavigationView() {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.Home:
indexSelected=0;
markTheItemSelected(indexSelected);
changeNameofTitleBar(indexSelected);
fragmentTodisplay(indexSelected);
break;
case R.id.SignIn:
indexSelected=1;
markTheItemSelected(indexSelected);
changeNameofTitleBar(indexSelected);
fragmentTodisplay(indexSelected);
break;
case R.id.SignOut:
indexSelected=2;
markTheItemSelected(indexSelected);
changeNameofTitleBar(indexSelected);
fragmentTodisplay(indexSelected);
break;
case R.id.AboutUs:
indexSelected=3;
markTheItemSelected(indexSelected);
changeNameofTitleBar(indexSelected);
fragmentTodisplay(indexSelected);
break;
case R.id.ContactUs:
indexSelected=4;
markTheItemSelected(indexSelected);
changeNameofTitleBar(indexSelected);
fragmentTodisplay(indexSelected);
break;
}
drawer.closeDrawers();
return true;
}
});
ActionBarDrawerToggle actionBarDrawerToggle=new ActionBarDrawerToggle(this,drawer,toolbar,R.string.openDrawer,R.string.closeDrawer){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
actionBarDrawerToggle.syncState();
}
private void fragmentTodisplay(int indexSelected) {
switch (indexSelected)
{
case 0:
Home obj=new Home();
FragmentTransaction transaction=getSupportFragmentManager().beginTransaction();
transaction.add(R.id.frame,obj,"HOME");
transaction.commit();
break;
}
}
private void markTheItemSelected(int indexSelected) {
navigationView.setCheckedItem(indexSelected);
}
private void changeNameofTitleBar(int indexSelected) {
toolbar.setTitle(nameOnTitleBar[indexSelected]);
}
}
And the fragment code is as follows:
Home.java
package com.example.hsports.weddingplanner.Fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.hsports.weddingplanner.R;
/**
* Created by I324671 on 11/27/2016.
*/
public class Home extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return inflater.inflate(R.layout.fragmentaboutus,container,false);
}
}
my navoigation_drawer.xml is this:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single"
>
<item
android:id="#+id/Home"
android:title="HOME"
/>
<item
android:id="#+id/SignIn"
android:title="SIGN-IN"
/>
<item
android:id="#+id/SignOut"
android:title="SIGN-OUT"
/>
</group>
<item android:title="OTHER">
<menu>
<item
android:id="#+id/AboutUs"
android:title="ABOUT US"/>
<item
android:id="#+id/ContactUs"
android:title="CONTACT US"
/>
<item
android:id="#+id/Share"
android:title="SHARE"
/>
</menu>
</item>
</menu>
fragmentaboutus.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Home"
/>
</LinearLayout>
Now when I click on Home icon in the navigation drawer the particular Home fragment doesn't gets displayed.
This is app_bar_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
>
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="#+id/toolbar"
app:popupTheme="#style/AppTheme.PopupOverlay"
android:background="#color/blue"
>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frame"
></FrameLayout>
</android.support.design.widget.CoordinatorLayout>
Activity_front_page.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/navigation_drawer"
android:id="#+id/nav_view"
></android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Try replacing
transaction.add(R.id.frame, obj, "HOME");
with
transaction.replace(R.id.frame, obj, "HOME");

Categories

Resources