Navigation drawer on click issue upon extending activity - java

So i have extended this DrawerActivity to other activities and I can see the Navigation bar in the extended activities but the on item click listener doesnt work.
This is the drawer activity
public class DrawerActivity extends AppCompatActivity {
public DrawerLayout mDrawarlayout;
public ActionBarDrawerToggle mToggle;
public NavigationView mNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
mDrawarlayout = findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this, mDrawarlayout, R.string.open, R.string.close);
mDrawarlayout.addDrawerListener(mToggle);
mNavigationView = findViewById(R.id.navigationView);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupDrawerContent(mNavigationView);
}
public void selectItemDrawer(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.settings_drawer:
Toast.makeText(getApplicationContext(), "Clicked", Toast.LENGTH_LONG).show();
Intent anIntent = new Intent(getApplicationContext(), PatientSettingsActivity.class);
startActivity(anIntent);
//drawerLayout.closeDrawers();
break;
case R.id.logout:
Toast.makeText(getApplicationContext(), "Logout Clicked", Toast.LENGTH_LONG).show();
break;
case R.id.chat:
Toast.makeText(getApplicationContext(), "CHat Clicked", Toast.LENGTH_LONG).show();
break;
case R.id.history:
Toast.makeText(getApplicationContext(), "Hisotry Clicked", Toast.LENGTH_LONG).show();
break;
case R.id.db:
Toast.makeText(getApplicationContext(), "Dashboard Clicked", Toast.LENGTH_LONG).show();
break;
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawarlayout.closeDrawers();
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectItemDrawer(item);
return true;
}
});
}
}
This is the drawer activity xml
<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:id="#+id/drawer_layout"
tools:context=".DrawerActivity">
<android.support.design.widget.NavigationView
app:headerLayout="#layout/header"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#color/white"
app:itemTextColor="#color/primaryTextColor"
app:menu= "#menu/drawermenu"
android:id="#+id/navigationView"
android:layout_gravity = "start">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
This is how i have extended DrawerActivity
P.S this is what i followed
Same Navigation Drawer in different Activities
public class MapActivity extends DrawerActivity{
........}
And i have noticed that the on item click listener works when i run the DrawerActivity only

I solved my problem by following this tutorial below
http://mateoj.com/2015/06/21/adding-toolbar-and-navigation-drawer-all-activities-android/
and the github link
https://github.com/j-mateo/MultiActivityToolbar

Related

How do you use a toolbar across all activies

I have made a toolbar and Navigation Drawer java class along with its XML, it works perfectly.
Here is the code:
Java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
//This part is new for NavigationDrawer:
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.items, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ticket:
startActivity(new Intent(NavigationActivity.this, TicketMasterActivity.class));
break;
case R.id.recipe:
Intent goToRecipe = new Intent(NavigationActivity.this, RecipeSearchActivity.class);
startActivity(goToRecipe);
break;
case R.id.covid:
Intent goToCovid = new Intent(NavigationActivity.this, MainActivity_covid.class);
startActivity(goToCovid);
break;
case R.id.album:
Intent goToAlbum = new Intent(NavigationActivity.this, MainActivity.class);
startActivity(goToAlbum);
break;
case R.id.help:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.WelcomeTotal);
alertDialogBuilder.setMessage(R.string.WelcomeTotalMessage);
alertDialogBuilder.setPositiveButton("OK", (click2, arg) -> {
});
alertDialogBuilder.create().show();
}
return true;
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.ticket1) {
startActivity(new Intent(NavigationActivity.this, TicketMasterActivity.class));
} else if (id == R.id.recipe1) {
Intent goToRecipe = new Intent(NavigationActivity.this, RecipeSearchActivity.class);
startActivity(goToRecipe);
} else if (id == R.id.covid1) {
Intent goToCovid = new Intent(NavigationActivity.this, MainActivity_covid.class);
startActivity(goToCovid);
} else if (id == R.id.album1) {
Intent goToAlbum = new Intent(NavigationActivity.this, MainActivity.class);
startActivity(goToAlbum);
} else if (id == R.id.share) {
Toast.makeText(this, "this feature is not yet implemented", Toast.LENGTH_LONG).show();
} else if (id == R.id.send) {
Toast.makeText(this, "this feature is not yet implemented", Toast.LENGTH_LONG).show();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
XML:
<LinearLayout xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
android:id="#+id/toolbar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"/>
<androidx.drawerlayout.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<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:itemTextColor="#000000"
app:headerLayout="#layout/naviheader"
app:menu="#menu/navimenu"
tools:ignore="MissingClass" />
</androidx.drawerlayout.widget.DrawerLayout>
</LinearLayout>
I want to make it so that every activity uses this specific toolbar. And that every toolbar is preloaded with the items that I put inside in the java class. Is this possible and if so, how?
Thank you.
Create and Activity which will behave as a Parent Activity with your own custom toolbar.
Extend that activity where ever you want.

NavigationDrawerActivity with BottomNavigationActivity

I am trying to use NavigationDrawerActivity with a BottomNavigationActivity.
I have implemented NavigationDrawerActivity(Separate) first and saved BottomNavigationActivity(Separate) in HomeActivity but a black screen comes out while running app, with no errors!
My HomeActivity
public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close){
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item != null && item.getItemId() == android.R.id.home) {
if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
drawerLayout.closeDrawer(Gravity.RIGHT);
}
else {
drawerLayout.openDrawer(Gravity.RIGHT);
}
}
return false;
}
};
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
navigationView.setCheckedItem(R.id.home);
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.search:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SearchFragment()).commit();
break;
case R.id.home:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
break;
}
drawerLayout.closeDrawer(GravityCompat.END);
return true;
}
}
Code for My HomeFragment consisting BottomNavigationView
public class HomeFragment extends Fragment {
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
BottomNavigationView bottomNav = view.findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
return view;
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.tours:
selectedFragment = new ToursFragment();
break;
case R.id.hotel:
selectedFragment = new HotelFragment();
break;
case R.id.maps:
selectedFragment = new SearchFragment();
break;
}
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content, selectedFragment);
transaction.commit();
return true;
}
};
}
I wanted to use Navigation Drawer Activity with BottomNavigationActivity in this code and wanted to show BottomNavigationActivity in only one fragment.
I solved this problem, but first we forget HomeFragment, I deleted almost everything except View there.
I put BottomNavigationActivity with Navigation Drawer Activity in one Activity
Here is my xml from HomeActivity (i.e. it is MainActivity)
<?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"
tools:context=".MainActivity"
>
<androidx.drawerlayout.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:openDrawer="end"
android:fitsSystemWindows="true">
<RelativeLayout
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"
android:layout_below="#+id/toolbar"/>
<FrameLayout
android:id="#+id/fragment_container_bottom"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/bottom_navigation"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:layout_alignParentBottom="true"
app:itemHorizontalTranslationEnabled="false"
app:menu="#menu/bottom_nav_menu" />
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="end"
app:headerLayout="#layout/nav_helder"
app:menu="#menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
</RelativeLayout>
And submitted to HomeActivity to BottomNavigationActivity
setVisibility (View.GONE);
public class HomeActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
private DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBarDrawerToggle actionBarDrawerToggle;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewCompat.setLayoutDirection(toolbar, ViewCompat.LAYOUT_DIRECTION_RTL);
toolbar.setTitle("Paris Tours ");
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ToursFragment()).commit();
navigationView.setCheckedItem(R.id.nav_view);
}
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
//I added this if statement to keep the selected fragment when rotating the device
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_bottom,
new ToursFragment()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.tours:
selectedFragment = new ToursFragment();
break;
case R.id.hotel:
selectedFragment = new HotelFragment();
break;
case R.id.maps:
selectedFragment = new MapsFragment();
break;
case R.id.taxi:
selectedFragment = new TaxiFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_bottom,
selectedFragment).commit();
return true;
}
};
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
if(drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
drawerLayout.closeDrawer(Gravity.RIGHT);
}
else {
drawerLayout.openDrawer(Gravity.RIGHT);
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.search:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SearchFragment()).commit();
bottomNavigationView.setVisibility(View.GONE);
break;
case R.id.home:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FavouriteFragment()).commit();
bottomNavigationView.setVisibility(View.VISIBLE);
break;
case R.id.tours:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SettingsFragment()).commit();
bottomNavigationView.setVisibility(View.GONE);
break;
}
drawerLayout.closeDrawer(GravityCompat.END);
return true;
}
}

Android navigation drawer icon not working [duplicate]

This question already has an answer here:
Navigation drawer not opening from cutom menu button
(1 answer)
Closed 5 years ago.
I had a working navigation drawer, but I changed the toolbar, and now the icon of the navigationdrawer stopped working. It works again after pulling the drawer out. This is the relevant code:
MainActivity.java
//Drawer and fragments variables
private FragmentManager fragmentManager;
private ActionBarDrawerToggle toggle;
private DrawerLayout drawer;
//Searchbar variables
private Toolbar toolbar, searchtollbar;
private Menu search_menu;
private MenuItem item_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setup toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setSearchtollbar();
//Setup navigationdrawer
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(0).setChecked(true);
//Setup fragments
fragmentManager = getSupportFragmentManager();
try{
fragmentManager.beginTransaction().replace(R.id.container, HomeFragment.class.newInstance()).commit();
}catch(Exception e){
handleError(e);
}
}
#Override
public void onBackPressed() {
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) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
toggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
}
#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.
//noinspection SimplifiableIfStatement
Log.i("TAG", "Item clicked: "+item.getItemId());
if (toggle.onOptionsItemSelected(item)) {
return true;
}
switch(item.getItemId()){
case R.id.action_settings:{
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Log.i("TAG", "Navigation item clicked: " + id);
Class fragmentClass;
Fragment fragment = null;
switch(id) {
...
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
handleError(e);
}
fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
main_activity.xml
<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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="#+id/toolbar"
layout="#layout/app_bar_main"/>
<include layout="#layout/app_bar_main_search"
android:visibility="invisible"/>
<include
layout="#layout/main_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/toolbar"/>
</RelativeLayout>
<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:visibility="gone"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
Now my questions are:
Why doesn't the hamburger icon work the first time?
Why does it start working after pulling the navigation drawer out?
Thanks in advance.
Use This code :
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
toggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
toggle.setHomeAsUpIndicator(R.drawable.menu); //set your own
// setting click listener on hamburger icon
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDrawerLayout.openDrawer(Gravity.START);
}
}
});
// setting listerner on drawer
mDrawerLayout.addDrawerListener(toggle);
toggle.syncState();
after setting drawer listener add toggle sync and check
drawer.addDrawerListener(toggle);
toggle.syncState();

PreferenceFragmentCompat doesn't show

I need help to fix a problem with PreferenceFragmentCompat, which simply doesn't shows, no error in console, no message, nothing, just a blank page.
The fragment is shown as a result of the selection of an element in a navigation drawer. Here's the Activity 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"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="false">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/list_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<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_marginBottom="24dp"
android:layout_marginEnd="24dp"
app:elevation="12dp"
app:fabSize="normal"
app:rippleColor="#color/nowControlsNormal"
app:srcCompat="#android:drawable/ic_popup_sync" />
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/drawer"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/drawer_top"
app:itemIconTint="#color/nowBlack"
app:itemTextColor="#color/nowBlack"
app:menu="#menu/drawer_menu" />
</android.support.v4.widget.DrawerLayout>
Here's the activity Java:
public class HomeActivity extends AppCompatActivity {
SharedPreferences settings;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
NavigationView nav;
TextView drawerUsername;
FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settings = getSharedPreferences("NowCLOUD", 0);
setContentView(R.layout.activity_home);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
nav = (NavigationView) findViewById(R.id.drawer);
fab = (FloatingActionButton) findViewById(R.id.fab);
View headerView = nav.getHeaderView(0);
drawerUsername = (TextView) headerView.findViewById(R.id.drawer_username);
fab.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//TODO: Gestire aggiornamento al click della FAB
}
});
getSupportActionBar().setTitle("Home");
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportFragmentManager().beginTransaction()
.add(R.id.list_container, HomeFragment.newInstance())
.commit();
drawerUsername.setText(settings.getString("username", "Error"));
nav.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
displayView(menuItem.getItemId());
return true;
}
});
}
public void displayView(int viewId) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (viewId) {
case R.id.drawer_home:
fragment = HomeFragment.newInstance();
title = "Home";
break;
case R.id.drawer_settings:
fragment = SettingsFragment.newInstance();
title = "Settings";
break;
}
if (fragment != null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.list_container, fragment)
.commit();
}
// set the toolbar title
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
Here's the Fragment's XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.preference.PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<android.support.v7.preference.PreferenceCategory
android:title="#string/settings_synchronization">
<android.support.v7.preference.SwitchPreferenceCompat
android:key="auto_updates"
android:title="#string/settings_auto_sync" />
</android.support.v7.preference.PreferenceCategory>
</android.support.v7.preference.PreferenceScreen>
Here's the Fragment's Java:
public class SettingsFragment extends PreferenceFragmentCompat {
View rootView;
#Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
addPreferencesFromResource(R.xml.fragment_settings);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
//rootView = inflater.inflate(R.xml.fragment_settings,container,false);
return rootView;
}
#Override
public PreferenceFragmentCompat getCallbackFragment() {
return this;
}
public static SettingsFragment newInstance() {
Bundle args = new Bundle();
SettingsFragment fragment = new SettingsFragment();
fragment.setArguments(args);
return fragment;
}
}
I've removed all of the code which was useless for this purpose. Sorry for the huge amount of code.
I've figured it out by myself:
when you are using preferencefragment you cannot override the onCreateView method, or you'll get a blank screen.

Toolbar doesn't work with navigation drawer and multiple activities

I'm trying to develop an app for bikes with multiple activities.
I developed a navigation drawer with multiple activities and toolbar instead of actionbar. In the main activity(TimerActivity), the toolbar works, but it doesn't works in the other activities when I click on the icon_drawer (it works only with the swipe). How can I fix this problem?
It seems that the toolbar is covered by another layout located above.
Sorry for bad english.
TimerActivity.java
public class TimerActivity extends ActionBarActivity {
private static String CLASS_NAME;
private Vibrator vibrate;
private Notify notify;
protected Toolbar toolbar;
protected DrawerLayout drawerLayout;
protected ActionBarDrawerToggle drawerToggle;
public ListView leftDrawerList;
protected ArrayList<navDrawerItems> NavDrawerItems;
protected NavDrawerListAdapter adapter;
private TypedArray navMenuIcons;
protected String[] navMenuTitles;
private CharSequence mTitle;
private LinearLayout linearLayout;
protected FrameLayout frameLayout;
public TimerActivity() {
CLASS_NAME = getClass().getName();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(CLASS_NAME, "onCreate");
setContentView(R.layout.activity_main);
frameLayout = (FrameLayout) findViewById(R.id.frame_container);
initView();
toolbar.setTitle("Navigation Drawer");
setSupportActionBar(toolbar);
initDrawer();
leftDrawerList.setOnItemClickListener(new SlideMenuClickListener());
}
protected void initView() {
//load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
//nav drawer icons from resources
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
leftDrawerList = (ListView) findViewById(R.id.left_drawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
NavDrawerItems = new ArrayList<navDrawerItems>();
//adding nav drawer items to array
//Home
NavDrawerItems.add(new navDrawerItems(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
//User
NavDrawerItems.add(new navDrawerItems(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
//Map
NavDrawerItems.add(new navDrawerItems(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
//Routes
NavDrawerItems.add(new navDrawerItems(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
//Camera
NavDrawerItems.add(new navDrawerItems(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
//Weather
NavDrawerItems.add(new navDrawerItems(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
//Recycle the typed array
navMenuIcons.recycle();
//setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),NavDrawerItems);
leftDrawerList.setAdapter(adapter);
}
protected void initDrawer() {
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
private void gotoRoutes() {
Log.d(CLASS_NAME, "gotoRoutes");
Intent routes = new Intent(this, RoutesActivity.class);
startActivity(routes);
}
/**
* Called when the settings button is clicked on.
*
* #param view
* the button clicked on
*/
public void gotoSettings(View view) {
Log.d(CLASS_NAME, "gotoSettings");
Intent settings = new Intent(this, SettingsActivity.class);
startActivity(settings);
}
private void gotoHome() {
Log.d(CLASS_NAME, "gotoHome");
Intent timer = new Intent(this, TimerActivity.class);
timer.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(timer);
}
public void gotoMap() {
Log.d(CLASS_NAME, "gotoMap");
Intent map = new Intent(this, MapActivity.class);
startActivity(map);
}
public void gotoPhoto() {
Log.d(CLASS_NAME, "gotoPhoto");
Intent photo = new Intent(this, PhotoActivity.class);
startActivity(photo);
}
public void shareActivity() {
Log.d(CLASS_NAME, "shareActivity");
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
gotoHome();
return true;
case R.id.menu_settings:
gotoSettings(null);
return true;
case R.id.menu_routes:
gotoRoutes();
return true;
case R.id.menu_map:
gotoMap();
return true;
case R.id.menu_photo:
gotoPhoto();
return true;
case R.id.menu_share:
shareActivity();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void notification(String title, String message) {
notify.notify(title, message);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(CLASS_NAME, "onDestroy");
}
#Override
public void onRestart() {
super.onRestart();
Log.d(CLASS_NAME, "onRestart");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(CLASS_NAME, "onCreateOptionsMenu");
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
/**
* Keep the screen on depending on the stay awake setting
*/
protected void stayAwakeOrNot() {
Log.d(CLASS_NAME, "stayAwakeOrNot");
Settings settings = ((OnYourBike) getApplication()).getSettings();
if (settings.isCaffeinated(this)) {
// Log.i(CLASS_NAME, "Staying awake");
getWindow()
.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
// Log.i(CLASS_NAME, "Not staying awake");
getWindow().clearFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
public void takePhoto(View view){
Log.d(CLASS_NAME, "takePhoto");
//if(camera.hasCamera() && camera.hasCameraApplication()){
// camera.takePhoto();
Intent photo = new Intent(this, PhotoActivity.class);
startActivity(photo);
}
public void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch(position){
case 0:
Intent intent1 = new Intent(this, CounterActivity.class);
startActivity(intent1);
finish();
break;
case 1:
Intent intent2 = new Intent(this, UserActivity.class);
startActivity(intent2);
finish();
break;
case 2:
Intent intent3 = new Intent(this, MapActivity.class);
startActivity(intent3);
finish();
break;
case 3:
Intent intent4 = new Intent(this, RoutesActivity.class);
startActivity(intent4);
finish();
break;
case 4:
Intent intent5 = new Intent(this, PhotoActivity.class);
startActivity(intent5);
finish();
break;
case 5:
Intent intent6 = new Intent(this, FragmentWeather.class);
startActivity(intent6);
finish();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
leftDrawerList.setItemChecked(position,true);
leftDrawerList.setSelection(position);
//setTitle(navMenuTitles[position]);
//drawerLayout.closeDrawer(leftDrawerList);
drawerLayout.closeDrawer(leftDrawerList);
toolbar.setTitle(navMenuTitles[position]);
}
else{
// error in creating fragment
Log.e("TimerActivity", "Error in creating fragment");
}
}
class SlideMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
displayView(position);
}
}
}
activity_main.xml (layout for TimerActivity)
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="7dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
</LinearLayout>
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|start"
android:background="#A0E843"
android:divider="#eee"
android:dividerHeight="1dp" />
</android.support.v4.widget.DrawerLayout>
UserActivity.java
public class UserActivity extends TimerActivity {
private int position;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_user);
getLayoutInflater().inflate(R.layout.activity_user, frameLayout );
leftDrawerList.setItemChecked(position,true);
toolbar = (Toolbar) findViewById(R.id.toolbar);
//frameLayout = (FrameLayout) findViewById(R.id.frame_container);
toolbar.setTitle("Useeeer activity");
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
setSupportActionBar(toolbar);
super.initView();
super.initDrawer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.user, menu);
return true;
}
}
user_activity.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="7dp" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="#layout/toolbar" />
</FrameLayout>
<!-- Framelayout to display Fragments -->
<!-- navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|start"
android:background="#A0E843"
android:divider="#eee"
android:dividerHeight="1dp" />
</android.support.v4.widget.DrawerLayout>
toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.Toolbar>
what i see from your codes is in the working activity you use toolbar in this way :
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
</LinearLayout>
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
which is true!
but the other layout does not follow this structure , its like this :
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="#layout/toolbar" />
</FrameLayout>
try to fix this and tell me if it works!
I have had problems like this before. Your activities could be taking the focus away from your toolbar.
In your Activity XML which contains your toolbar, try adding these to your <Toolbar> item in the .xml file:
android:descendantFocusability="false
android:focusable="false"
Try to change activity_main.xml - move the toolbar outside to DrawerLayout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar" />
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:elevation="7dp" >
</LinearLayout>
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|start"
android:background="#A0E843"
android:divider="#eee"
android:dividerHeight="1dp" />
</android.support.v4.widget.DrawerLayout>

Categories