This question already has answers here:
Android Navigation Drawer click Event Issue
(2 answers)
Closed 6 months ago.
How to handle menu item clicks on NavigationView in Main Activity?
NavigationView navigationView = findViewById(R.id.nav_view);
I am using "Navigation Drawer Activity" template from latest Android Studio (2021.2.1 Patch 2) as a start.
Thanks.
Here is what I did hope this helps:
DrawerLayout drawerLayout = view.findViewById(R.id.drawerLayout);
view.findViewById(R.id.imageMenu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
And then it will call this function when drawer button is clicked to open the drawer
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.miItem1){
}
if (id == R.id.miItem2){
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.ProfileFragment, fragment);
transaction.commit();
//startActivity(new Intent(getActivity(), PopFragment.class));
}
if (id == R.id.miItem3){
profileOrCoverPhoto = "image";
showImagePicDialog();
}
if (id == R.id.miItem4){
showNamephoneupdate("name");
}
if (id == R.id.miItem5){
showPasswordChangeDailog();
}
if (id == R.id.miItem7){
firebaseAuth.signOut();
startActivity(new Intent(getActivity(), SplashScreen.class));
getActivity().finish();
}
if (id == R.id.miItem8){
showdeleteaccountdialog();
}
return true;
}
Related
I am using common Navigation drawer for all activities and fragments but when I am clicking on same item of Navigation drawer also it inflating the same screen. What I want is the same item should not be loaded for second time.
This is my code:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (id == R.id.nav_profile) {
Intent i = new Intent(MainFragmentsActivity.this, ProfileActivity.class);
startActivity(i);
drawer.closeDrawer(GravityCompat.START);
}
}
You should not use common navigation drawer for all activities and fragments. Common design pattern is showing different fragments on the main activity for the navigation drawer menu items. And if the user navigates inside any fragment you should open an activity without any navigation drawer but with a back arrow in action bar.
Now if you dont want to show the same fragment then in
onNavigationItemSelected you can write the logic like below -
Fragment fragment = getSupportFragmentManager().findFragmentByTag("TAG");
if (fragment == null)
{
Create and attach new fragment
}else{
//Do not do anything.
}
Simple thing, store clicked view'd id to a variable and compare if its the same,
int id; // use this variable to store id of clicked view.
#Override public boolean onNavigationItemSelected(MenuItem item) {
if(id != item.getItemId) {
id = item.getItemId(); // store clicked id in variable
// Do your clicking stuffs here...
if (id == R.id.nav_profile) {
Intent i = new Intent(MainFragmentsActivity.this, ProfileActivity.class);
startActivity(i);
drawer.closeDrawer(GravityCompat.START);
}
}
}
For fragments:
if (id == R.id.nav_things_to_do) {
if (id == R.id.nav_things_to_do && viewPager.getCurrentItem() != 0) {
Intent main1 = new Intent(getApplicationContext(), MainFragmentsActivity.class);
main1.putExtra("position", 0);
main1.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
main1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
main1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
finish();
startActivity(main1);
overridePendingTransition(0, 0);
drawer.closeDrawer(GravityCompat.START);
}
else {
drawer.closeDrawer(GravityCompat.START);
}
}
if (id == R.id.nav_all_tasks) {
if (id == R.id.nav_all_tasks && viewPager.getCurrentItem() != 1) {
Intent main2 = new Intent(getApplicationContext(), MainFragmentsActivity.class);
main2.putExtra("position", 1);
main2.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
main2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
main2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
finish();
startActivity(main2);
overridePendingTransition(0, 0);
drawer.closeDrawer(GravityCompat.START);
}
else {
drawer.closeDrawer(GravityCompat.START);
}
}
For Activities:
if (id == R.id.nav_images) {
try {
Intent i = new Intent(MainFragmentsActivity.this,
SelectFilesActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
drawer.closeDrawer(GravityCompat.START);
} catch (Exception e) {
e.printStackTrace();
}
}
Hello i'm not an expert in android development. I'm trying to develop an application using the Navigation drawer template of Android Studio. So, i created a new project using this template. But when i run the program an click on a menu item, the view doesn't change. So i searched everywhere on internet i didn't see how i can handle this.
This is the code provided by studio
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
What i want to achieve is to replace the current view with the appropriate view which menu's is cliked.
Create Gallery.Java and paste this code:
public class Gallery extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_gallery,null);
}
}
And in your navigation drawer file paste this code:
if (id == R.id.nav_gallery)
{
Fragment fragment = new Gallery();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.framelayout, fragment).commit();
}
I have 2 activites:
- LoginActivity: it will handle the login stuff later
- MainActivity: the main app, all of the functions will be provided on fragments.
I want to properly use the back stack, but I can't.
What I want (but can't) achieve:
App starts with Login screen. I login (right now press the Start button), after that the main screen appears and the first fragment loads.
Now if I press the back button, the app closes, and that's how it should work, it must not go back to the login screen with a simple back button press.
But now if I click logout (and the Login screen appears), and I press the back button, the app takes me back to the main screen, what is really not ok. If I log out, from the login screen the back button should close the app.
And another problem, regarding also backstack, and fragments:
I have 3 fragments: first, second and third. If I open them after each other (within the main activity of course), and I press the back button, I want it to take me back to the previously opened fragment, or if there's no previous, close the app.
Now it makes it, opens the previous fragment, but at the same time it closes the complete app. (I can see that they are happening right after each other)
What's missing? What should be modified to achieve this (normal) behavior?
Thanks!
My code:
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static final String SP_DATA = "SP_DATA";
public static final String FB_LOGIN_STATUS = "FB_LOGIN_STATUS";
public static final String FLRT = "FLRT";
public SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
sharedPreferences = getSharedPreferences(SP_DATA, MODE_PRIVATE);
boolean bAlreadyLoggedIn = sharedPreferences.getBoolean(FB_LOGIN_STATUS, false);
if (bAlreadyLoggedIn) {
Log.d(FLRT, "Already logged in");
}
else {
Log.d(FLRT, "Not logged in");
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
showFragment(new FirstFragment(),"FirstFragment");
Button btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logout();
showActivity(MainActivity.this, LoginActivity.class);
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
private void showActivity(Context context_fromActivity, Class<?> class_toActivty){
Intent intent = new Intent(context_fromActivity, class_toActivty);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void logout() {
Log.d(FLRT, "Logging out...");
sharedPreferences = getSharedPreferences(SP_DATA, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(FB_LOGIN_STATUS, false);
editor.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_first_layout) {
showFragment(new FirstFragment(), "FirstFragment");
}
else if (id == R.id.nav_second_layout) {
showFragment(new SecondFragment(), "SecondFragment");
}
else if (id == R.id.nav_third_layout) {
showFragment(new ThirdFragment(), "ThirdFragment");
}
else if (id == R.id.nav_share) {
}
else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void showFragment(Fragment fragment, String sFragmentTAG) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (fragmentManager.findFragmentByTag(sFragmentTAG) != null) {
Log.d(FLRT, "Fragment found, using existing one: " + sFragmentTAG);
fragment = fragmentManager.findFragmentByTag(sFragmentTAG);
}
fragmentTransaction.replace(R.id.fragmentContainer, fragment, sFragmentTAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
}
LoginActivity:
public class LoginActivity extends AppCompatActivity {
public static final String SP_DATA = "SP_DATA";
public static final String FB_LOGIN_STATUS = "FB_LOGIN_STATUS";
public static final String FLRT = "FLRT";
public SharedPreferences sharedPreferences;
private Button btn_start;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_start = (Button) findViewById(R.id.btn_start);
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
showActivity(LoginActivity.this, MainActivity.class);;
}
});
}
private void showActivity(Context context_fromActivity, Class<?> class_toActivty){
Intent intent = new Intent(context_fromActivity, class_toActivty);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void login() {
Log.d(FLRT, "Logging in...");
sharedPreferences = getSharedPreferences(SP_DATA, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(FB_LOGIN_STATUS, true);
editor.commit();
}
}
About switching between Activities.
One important thing.
In showActivity() use finish() to kill current Activity when going to another. If it doesn't help - see below.
Try to use also FLAG_ACTIVITY_NEW_TASK with your current flag, because FLAG_ACTIVITY_CLEAR_TOP will close only Activities in task above current Activity, but not below.
So, it would be this: intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
Another option is to use: FLAG_ACTIVITY_CLEAR_TASK only - new Activity will clear the task and become root in it.
If both won't help - use android:launchMode = "singleInstance" in Manifest for each Actitivy.
About Fragments - I see a little mistake in your code: it calls super.onBackPressed(); before popping Fragment from BackStack
I would change like this:
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
!! Also you should test this line: getFragmentManager().getBackStackEntryCount() > 0 with 0 and 1 in condition (because in current implementation in my project FragmentContainer is considering as first, zero value in a BackStack). Just test 0 and 1 to see which works.
Thanks.
PS. Few more tips.
You can declare FragmentManager fragmentManager in your Activity in order to create it one time only in onCreate(). It would be better than get it each time.
Consider change this:
if (id == R.id.nav_first_layout) {
showFragment(new FirstFragment(), "FirstFragment");
}
else if (id == R.id.nav_second_layout) {
showFragment(new SecondFragment(), "SecondFragment");
}
else if (id == R.id.nav_third_layout) {
showFragment(new ThirdFragment(), "ThirdFragment");
}
else if (id == R.id.nav_share) {
}
else if (id == R.id.nav_send) {
}
To:
switch (item.getItemId()) {
case R.id.nav_first_layout:
showFragment(new FirstFragment(), "FirstFragment");
break;
case ...
}
and so on. The code would be more pretty :)
I have made navigation drawer in Android Studio.
Right now each fragment from drawer is leading to nowhere.
I need to know how can I switch between fragments and click on each one
I know i need to make new fragment, but what method to use so I can click on Settings from navigation drawer so it lead me to fragment Share?
Here is my code;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You are in the right direction. Just add the Fragment class in each of the Navigation items like below
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new DefaultFragment();
fragmentManager.beginTransaction().replace(R.id.first_container, fragment).commit();
} else if (id == R.id.nav_gallery) {
fragment = new ItemListFragment();
fragmentManager.beginTransaction().replace(R.id.first_container, fragment).commit();
}
}
at the end of onCreate(Bundle savedInstanceState)method, you can set the default Fragment to open on Activity load.
FragmentManager fragmentManager = getSupportFragmentManager();
DefaultFragment fragment = new DefaultFragment();
fragmentManager.beginTransaction().replace(R.id.first_container, fragment).commit();
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.`enter code here`
int id = item.getItemId();
FragmentManager fragmentManager =getSupportFragmentManager();
GoogleMap googleMap =getSupportFragmentManager();
if (id == R.id.alarme){
} else if (id == R.id.map) {
fragmentManager.beginTransaction().replace(R.id.contenedor,new mapposta()).commit();
} else if (id == R.id.parametre) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
I've searched all over Google trying to find the answer but haven't been able to find an answer. I'm using the "Create Navigation Drawer Activity" template in Android Studio. How do I add my fragments to the Navigation Drawer?
Here's where I assume I add the fragments:
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camara) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Based on tutorials I've seen, I've tried adding the following in the if statements with no success:
fragment = new ItemFragment();