When I try to switch my side fragments in the sidebar from one to another it stays fixated on message fragment. The highlight only changes between 2 fragments: forum and message.
My code:
package com.example.ius;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
public class MainPub extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_pub);
drawer = findViewById(R.id.drawer_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.nav_draw_open, R.string.nav_draw_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if(savedInstanceState==null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MessageFragment()).commit();
navigationView.setCheckedItem(R.id.mainForum);}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.mainForum:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MessageFragment()).commit();
break;
case R.id.messages:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MessageFragment()).commit();
break;
case R.id.profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MessageFragment()).commit();
break;
case R.id.share:
Toast.makeText(this, "I share se", Toast.LENGTH_SHORT).show();
break;
case R.id.support:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MessageFragment()).commit();
break;
case R.id.logOut:
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(this, MainActivity.class));
finish();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
The thing is only logout fragment works, while others don't open. Also, the side question is when I select fragments from the side I can only select Forum and Messaging, in which Forum doesn't change but only the sidebar highlights.
Thanks in advance for the help :)
I solved the problem by changing the fragment opening new code:
package com.example.ius;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
public class MainPub extends AppCompatActivity {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_pub);
drawer = findViewById(R.id.drawer_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
//navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.nav_draw_open, R.string.nav_draw_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//NOVO
setupDrawerContent(navigationView);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ForumFragment()).commit();
navigationView.setCheckedItem(R.id.mainForum);
}
}
//NOVO
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
Class fragmentClass;
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.mainForum:
fragmentClass = ForumFragment.class;
break;
case R.id.messages:
fragmentClass = MessageFragment.class;
break;
case R.id.profile:
fragmentClass = ProfileFragment.class;
break;
case R.id.share:
Toast.makeText(this, "I share se", Toast.LENGTH_SHORT).show();
break;
case R.id.support:
fragmentClass = SupportFragment.class;
break;
default:
fragmentClass = ForumFragment.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment).commit();
// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);
// Set action bar title
setTitle(menuItem.getTitle());
// Close the navigation drawer
drawer.closeDrawers();
}
// ...
/* #Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.mainForum:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MessageFragment()).commit();
break;
case R.id.messages:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MessageFragment()).commit();
break;
case R.id.profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MessageFragment()).commit();
break;
case R.id.share:
Toast.makeText(this, "I share se", Toast.LENGTH_SHORT).show();
break;
case R.id.support:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new MessageFragment()).commit();
break;
case R.id.logOut:
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(this, MainActivity.class));
finish();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}*/
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
Related
Hello all I have an activity with three fragments.When the app launches it directly displays my activity with activity Name.and on clicking to fragments inside navigation drawer the toolbar title changes.Now I just want to replace the Toolbar title just of Activity with icon. for this I used setlogo.However I wish to make the icon visible just at the first time when the app launches.I mean when I select fragment I should be able to replace the icon by fragment name.
this is my code of activity.Please help
package com.example.user.educationhunt;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.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.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.user.educationhunt.fragment.NearMe;
import com.example.user.educationhunt.fragment.Register;
import com.example.user.educationhunt.fragment.Search;
import com.example.user.educationhunt.fragment.Settings;
import com.example.user.educationhunt.pojos.feedbackData;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class EduHunt extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edu_hunt);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setLogo(R.mipmap.edutext);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.flContent, new Search());
tx.commit();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.search:
fragmentClass = Search.class;
break;
case R.id.settings:
fragmentClass = Settings.class;
break;
case R.id.register:
fragmentClass = Register.class;
break;
case R.id.nearme:
fragmentClass = NearMe.class;
break;
default:
fragmentClass = Search.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()){
case R.id.our_team:
final Dialog dialog=new Dialog(this);
dialog.setContentView(R.layout.activity_our_team);
dialog.show();
return true;
case R.id.feedback:
startActivity(new Intent(EduHunt.this,SendFeedback.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.education_hunt, menu);
return true;
}
}
this is my toolbar.xml
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="?attr/colorPrimaryDark">
</android.support.v7.widget.Toolbar>
Well, you need to customize your toolbar: as below:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:layout_height="56dp"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorPrimary"
app:theme="#style/ToolbarSearchView"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:orientation="horizontal"
android:id="#+id/ll_navi"
android:background="#color/colorPrimary"
android:gravity="center_vertical"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="46dp"
android:paddingLeft="5dp"
....
/>
<TextView
android:layout_width="match_parent"
android:layout_height="46dp"
android:paddingLeft="5dp"
..../>
</LinearLayout>
</android.support.v7.widget.Toolbar>
And after that you just need to handle the visibility of image and text as per your requirement.
Edit
Include the toolbar layout in your activity's layout as:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:background="#drawable/bg">
<include
android:id="#+id/tool_bar"
layout="#layout/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
........
</LineraLayout>
and then in your Activity access toolbar as:
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView txtTitle = (TextView) findViewById(R.id.toolbar_title);
Try this.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.yourIcon);
toolbar.setTitle("");
Change it here:
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
toolbar.setNavigationIcon(R.drawable.yourIcon);
switch (menuItem.getItemId()) {
case R.id.search:
fragmentClass = Search.class;
//Change it here
toolbar.setNavigationIcon(R.drawable.cutomIcon);
break;
case R.id.settings:
//Change it here
toolbar.setNavigationIcon(R.drawable.cutomIcon);
fragmentClass = Settings.class;
break;
case R.id.register:
//Change it here
toolbar.setNavigationIcon(R.drawable.cutomIcon);
fragmentClass = Register.class;
break;
case R.id.nearme:
//Change it here
toolbar.setNavigationIcon(R.drawable.cutomIcon);
fragmentClass = NearMe.class;
break;
default:
//Change it here
toolbar.setNavigationIcon(R.drawable.cutomIcon);
fragmentClass = Search.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
Try this,
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()) {
case R.id.search:
toolbar.setTitle("search");
fragmentClass = Search.class;
break;
case R.id.settings:
toolbar.setTitle("settings");
fragmentClass = Settings.class;
break;
case R.id.register:
fragmentClass = Register.class;
break;
case R.id.nearme:
fragmentClass = NearMe.class;
break;
default:
fragmentClass = Search.class;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
toolbar.setLogo(null);
}
navigation drawer, handling the back button to go to HomeFragment
This is SecurityFragment
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class SecurityFragment extends Fragment {
public SecurityFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_security, container, false);
}
}
This is the HomeFragment (When onBackPressed i just want the user to be directed to the homepage)current situation is that on onBackPressed the running application is destroyed
package sampleapp.razen.com.sampleapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.widget.Toast;
public class Menu extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
android.app.Fragment fragment = new MenuFragment(); // create a fragement object
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
//this the email icon on the home page
#Override
public void onClick(View view) {
String myEmail[]={"john#balloonventures.com"};
Intent sendMail = new Intent(Intent.ACTION_SEND);
sendMail.putExtra(Intent.EXTRA_EMAIL,myEmail);
sendMail.putExtra(Intent.EXTRA_SUBJECT,"(Type your subject)");
sendMail.setType("plain/text");
//incase you have to add something else put here
sendMail.putExtra(Intent.EXTRA_TEXT,"Your phone:+2547");
startActivity(sendMail);
}
});
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);
}
//taxi module
public void taxi_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.Taxi.class);
startActivity(timer);}
//host home module
public void hosthome_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.MainActivity.class);
startActivity(timer);}
//calling enterprenuers module
public void enter_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.SectionListView.class);
startActivity(timer);}
//calling UKV/ICV
public void ukvicv_id(View view){
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.UkvIcv_Home.class);
startActivity(timer);}
public void finacial_id(View view){
Intent finacial=new Intent(this,sampleapp.razen.com.sampleapp.FinacialHomePage.class);
startActivity(finacial);}
#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 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);
}
public void displayView(int viewId) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (viewId) {
case R.id.nav_12wks_program:
Intent timer=new Intent(this,sampleapp.razen.com.sampleapp.ExpandableListMainActivity.class);
startActivity(timer);
break;
case R.id.nav_emergency_contact:
Intent flow=new Intent(this,sampleapp.razen.com.sampleapp.EmergencyContact.class);
startActivity(flow);
break;
case R.id.nav_survey:
fragment = new SurveyFragment();
title = "Survey";
break;
case R.id.nav_psld:
fragment = new PsldFragment();
title = "Psld";
break;
case R.id.nav_security:
fragment = new SecurityFragment();
title = "All Volunteers Mu";
break;
case R.id.nav_ukv:
fragment = new UkvKiswaFragment();
title = "Ukv's kiswahili";
break;
case R.id.nav_agreement:
fragment = new AgreementFragment();
title = "Agreement ";
break;
case R.id.nav_njoro_geo:
fragment = new GeoNjoroFragment();
title = "Njoro Geography ";
break;
}
if (fragment != null) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
}
// set the toolbar title
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(title);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
} #SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displayView(item.getItemId());
return true;
}
}
Add your fragment transection to Fragment Backstack befor commit
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.addToBackStack( "tag" );
ft.commit();
Good afternoon,
I was following a tutorial to create a drawer menu for Android.
As programmed, came to me the need for when I go into a Fragment Class, wanted on the menu when you press on the Home, back to the Home (MainActivity) and not for another class.
I leave here my code of this project.
MainActivity.java
package pt.projects.bpn.menudrawerproject;
import android.content.res.Configuration;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
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.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
mDrawer.addDrawerListener(drawerToggle);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
private void setupDrawerContent(NavigationView nvDrawer) {
nvDrawer.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(MenuItem menuItem){
selectDrawerItem(menuItem);
return true;
}
});
}
private void selectDrawerItem(MenuItem menuItem) {
Fragment fragment = null;
Class fragmentClass;
switch (menuItem.getItemId()){
case R.id.nav_home_fragment:
fragmentClass = null;
break;
case R.id.nav_first_fragment:
fragmentClass = FirstFragment.class;
break;
case R.id.nav_second_fragment:
fragmentClass = SecondFragment.class;
break;
case R.id.nav_third_fragment:
fragmentClass = ThirdFragment.class;
break;
default:
fragmentClass = FirstFragment.class;
}
if(fragmentClass != null) {
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}
else {
FragmentManager fragmentManager = getSupportFragmentManager();
for(int i = 0; i < fragmentManager.getFragments().size(); ++i) {
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
Can you please clarify me how i can do that?
EDIT
I update the code for the tips from the comments bellow.
Now, the graphic layout take no changes.
Hi i have this problem with my navigation drawer. The drawer opens fine but i am having problems with the onClickListener. if an item on the drawer is clicked on it doesnt show the related layout instaed a black page shows. Please help
home.java
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.design.widget.NavigationView;
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.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.Toast;
public class home extends AppCompatActivity {
//Defining Variables
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
navigationView = (NavigationView) findViewById(R.id.navigation_view);
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if(menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.dashboard:
Toast.makeText(getApplicationContext(),"dashboard",Toast.LENGTH_SHORT).show();
Dashboard fragment = new Dashboard();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
break;
// For rest of the options we just show a toast on click
case R.id.profile:
Toast.makeText(getApplicationContext(),"profile",Toast.LENGTH_SHORT).show();
new Profile();
break;
case R.id.logs:
Toast.makeText(getApplicationContext(),"logs",Toast.LENGTH_SHORT).show();
new Logs();
break;
case R.id.statements:
Toast.makeText(getApplicationContext(),"statements",Toast.LENGTH_SHORT).show();
new Statements();
break;
case R.id.timeline:
Toast.makeText(getApplicationContext(),"timeliine",Toast.LENGTH_SHORT).show();
new Timeline();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(),"settings",Toast.LENGTH_SHORT).show();
new Settings();
break;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
break;
}
return true; }
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.openDrawer, R.string.closeDrawer){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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);
}
}
You're not switching fragments correctly in your case statements. You're only instantiating a new Fragment class and not doing anything with it. You need to do something like this:
Fragment fragment;
switch (menuItem.getItemId()){
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.dashboard:
Toast.makeText(getApplicationContext(),"dashboard",Toast.LENGTH_SHORT).show();
fragment = new Dashboard();
break;
// For rest of the options we just show a toast on click
case R.id.profile:
Toast.makeText(getApplicationContext(),"profile",Toast.LENGTH_SHORT).show();
fragment = new Profile();
break;
case R.id.logs:
Toast.makeText(getApplicationContext(),"logs",Toast.LENGTH_SHORT).show();
fragment = new Logs();
break;
case R.id.statements:
Toast.makeText(getApplicationContext(),"statements",Toast.LENGTH_SHORT).show();
fragment = new Statements();
break;
case R.id.timeline:
Toast.makeText(getApplicationContext(),"timeliine",Toast.LENGTH_SHORT).show();
fragment = new Timeline();
break;
case R.id.settings:
Toast.makeText(getApplicationContext(),"settings",Toast.LENGTH_SHORT).show();
fragment = new Settings();
break;
default:
Toast.makeText(getApplicationContext(),"Somethings Wrong",Toast.LENGTH_SHORT).show();
break;
}
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame,fragment);
fragmentTransaction.commit();
This way you're instantiating a fragment with a proper Fragment class each time, and at the end, replacing the frame with that particular fragment.
Digresion: It is recommended that you use newInstance to get the fragments and not the constructor. This is known as the Singleton design pattern.
package com.shafi.shafqat.listview;
import android.support.design.widget.NavigationView; 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;
import android.view.View; import android.widget.TextView; import
android.widget.Toast;
public class rawerActivity extends AppCompatActivity{
DrawerLayout drawer;
NavigationView navView;
Toolbar toolbar;
public void initNavDrawer(){
navView = (NavigationView) findViewById(R.id.navigation_view);
navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.bikes:
Toast.makeText(getApplicationContext(), "Bikes Selected", Toast.LENGTH_SHORT).show();
break;
case R.id.accessories:
Toast.makeText(getApplicationContext(), "Accessories Selected", Toast.LENGTH_SHORT).show();
break;
case R.id.contact:
Toast.makeText(getApplicationContext(), "Contact Us Selected", Toast.LENGTH_SHORT).show();
break;
case R.id.login:
Toast.makeText(getApplicationContext(), "Log In Selected", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
toolbar = (Toolbar) findViewById(R.id.toolbar);
View header = navView.getHeaderView(0);
TextView tv_email = (TextView)header.findViewById(R.id.user_name);
tv_email.setText("skshafqat#gmail.com");
drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
ActionBarDrawerToggle actionBarDrawerToggle =
new ActionBarDrawerToggle(this,drawer,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerClosed(View v){
super.onDrawerClosed(v);
}
#Override
public void onDrawerOpened(View v) {
super.onDrawerOpened(v);
}
};
drawer.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
}
I tested the same code yesterday and it worked. But now when I wanted to combine this code with another module it highlights the following drawer.addDrawerListener(actionBarDrawerToggle); line in red. when hover over it, it shows error cannot resolve method addDrawerListener(android.support.v7.app.ActionBarDrawerToggle).
Please help...