NavigationDrawer doesn't work, it's closing before doing something - java

I made an empty activity and then I changed it to a DrawerLayout and every time I open the Menu and click an item the drawer is closing and nothing happens like i'm just opening and closing it, can't doing anything else.
This is the layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/navigation_home_drawer">
<com.google.android.material.navigation.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/mainmenu"
>
</com.google.android.material.navigation.NavigationView>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.drawerlayout.widget.DrawerLayout>
And this is the Java Code
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private MapView mMapView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = findViewById(R.id.navigation_home_drawer);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView navigationView =findViewById(R.id.navigation);
navigationView.setNavigationItemSelectedListener(this);
mMapView = findViewById(R.id.map);
initGoogleMap(savedInstanceState);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.nav_home:{
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
finish();
break;
}
case R.id.nav_profile: {
Intent i = new Intent(this, ProfileActivity.class);
startActivity(i);
finish();
break;
}
case R.id.nav_settings: {
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
finish();
break;
}
}
return true;
}
}
Here's the menu layout
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/nav_home"
android:title="Home"
android:icon="#drawable/ic_home_black_24dp">
</item>
<item
android:id="#+id/nav_profile"
android:title="My Profile"
android:icon="#drawable/ic_person_black_24dp">
</item>
<item
android:id="#+id/nav_settings"
android:title="Settings"
android:icon="#drawable/ic_settigs">
</item>
</menu>
I also have the code for Map in this file, but it's not important, when I select an item from that menu I just want to change the activity to that, but nothing happens, only close the navigation, can you please tell me if I forgot to add something or what should I change to make the navigation work? Thank you in advance!

You can use this code to make navigation drawer :
NavigationView navigationView;
DrawerLayout drawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
navigationView = findviewbyid(R.id.nav_drawer_home);
drawerLayout = findviewbyid(R.id.drawer_home);
drawerLayout.requestLayout();
setUpNavigationView();
}
private void setUpNavigationView() {
navigationView.setNavigationItemSelectedListener(menuItem -> {
switch (menuItem.getItemId()) {
case R.id.nav_recharge:
break;
case R.id.nav_offers:
break;
case R.id.nav_rides:
break;
case R.id.nav_refer_friend:
break;
case R.id.nav_wallet:
break;
case R.id.nav_about_us:
break;
case R.id.nav_feedback:
break;
default:
break;
}
if (menuItem.isChecked())
menuItem.setChecked(false);
else
menuItem.setChecked(true);
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
});
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.openDrawer, R.string.closeDrawer) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawers();
return;
}
super.onBackPressed();
}
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_recharge"
android:icon="#drawable/ic_recharge_wallet"
android:title="Rechange Wallet" />
<item
android:id="#+id/nav_offers"
android:icon="#drawable/ic_offers"
android:title="Offer's" />
<item
android:id="#+id/nav_rides"
android:icon="#drawable/ic_ride"
android:title="Rides" />
<item
android:id="#+id/nav_refer_friend"
android:icon="#drawable/ic_refer_friend"
android:title="Refer a friend" />
<item
android:id="#+id/nav_wallet"
android:icon="#drawable/ic_wallet_transfer"
android:title="Wallet Transfer" />
<item
android:id="#+id/nav_about_us"
android:icon="#drawable/ic_about_us"
android:title="About Us" />
<item
android:id="#+id/nav_feedback"
android:icon="#drawable/ic_feedback"
android:title="Feedback" />
</group>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/home_content"/>
<com.google.android.material.navigation.NavigationView
android:clickable="true"
android:id="#+id/nav_drawer_home"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home"
app:menu="#menu/nav_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>

Related

How to open New Activity by clicking Navigation Drawer Item in Android

How can I open New Activity by clicking a Navigation Drawer Menu Item?
Share_Home.java
public class Share_Home extends AppCompatActivity {
private long backPressedTime;
private ActionBarDrawerToggle toggle;
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_home);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
tabs.getTabAt(1).select();
toggle = new ActionBarDrawerToggle(this, drawer, R.string.open, R.string.close);
drawer.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (toggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_share_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
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"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/nav_menu_item" />
<include
layout="#layout/activity_tabs_menu"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.drawerlayout.widget.DrawerLayout>
nav_menu_item.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/nav_Setting"
android:icon="#drawable/setting_icon"
android:title="#string/nav_Setting" />
<item
android:id="#+id/nav_Help"
android:icon="#drawable/help_icon"
android:title="#string/nav_Help" />
<item
android:id="#+id/nav_Ratings"
android:icon="#drawable/rating_icon"
android:title="#string/nav_Ratings" />
<item
android:id="#+id/nav_About"
android:icon="#drawable/about_icon"
android:title="#string/nav_About" />
</menu>
Set a NavigationItemSelectedListener to you NavigationView:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
int id=menuItem.getItemId();
if (id == R.id.xxx){
Intent newIntent = new Intent(this, NewActivity.class);
startActivity(newIntent);
}
return true;
}
});
Also change your layout.
Instead of:
<androidx.drawerlayout.widget.DrawerLayout >
<include layout="#layout/app_bar_main" />
<com.google.android.material.navigation.NavigationView/>
<include layout="#layout/activity_tabs_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
Use:
<androidx.drawerlayout.widget.DrawerLayout >
<include layout="#layout/app_bar_main" />
<com.google.android.material.navigation.NavigationView/>
</androidx.drawerlayout.widget.DrawerLayout>
moving the <include layout="#layout/activity_tabs_menu"/> inside the app_bar_main layout.
You have to override onNavigationItemSelected and check the id of the selected menu item and then open Activity:
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.activity1:
startActivity(new Intent(this, Activity1.class));
break;
case R.id.activity2:
startActivity(new Intent(this, Activity2.class));
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
And remember to add id to every item in menu layout:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/activity1"
android:title="#string/activity1" />
<item
android:id="#+id/activity2"
android:title="#string/activity2" />
</menu>
Here is how you can do it:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
final int itemId = item.getItemId();
if (itemId == R.id.nav_Setting) {
Intent newIntent = new Intent(getApplicationContext(), YourSettingActivity.class);
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(newIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.nav_menu_item, menu);
return super.onCreateOptionsMenu(menu);
}
You get a listener in your NavigationView that listens to the item pressed. So you can set the listener and then start an activity when a particular item is pressed in the NavigationDrawer, like so:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.menu_item_1:
Intent intent = new Intent(this, ItemActivity.class);
startActivity(intent);
break;
}
}
});

What code i need to input, and where, to switch to a different fragment once item is clicked?

on my activity_main_drawer i got many items but i don't know what code and where it goes to add for switching fragment
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_contests"
android:icon="#drawable/ic_menu_camera"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_rules"
android:icon="#drawable/irules"
android:title="#string/box_contest_rules" />
<item
android:id="#+id/nav_profile"
android:icon="#drawable/ic_baseline_face_24"
android:title="#string/profile_page" />
<item
android:id="#+id/nav_calendar"
android:icon="#drawable/icalendar"
android:title="#string/calendar_page" />
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/igallery"
android:title="#string/gallery_page" />
<item
android:id="#+id/nav_stats"
android:icon="#drawable/istats"
android:title="#string/stats_page" />
<item
android:id="#+id/nav_rank"
android:icon="#drawable/irank"
android:title="#string/rank_page" />
<item
android:id="#+id/nav_shop"
android:icon="#drawable/ishop"
android:title="#string/shop_page" />
<item
android:id="#+id/nav_setting"
android:icon="#drawable/ic_baseline_settings_24"
android:title="#string/setting_page" />
</group>
</menu>
this is the java HomePage where i am struggling to understand where and what code to add
public class HomePage extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home_page, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
}
and this is one of the fragment java as example.
public class GalleryFragment extends Fragment {
private GalleryViewModel galleryViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
galleryViewModel =
ViewModelProviders.of(this).get(GalleryViewModel.class);
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
final TextView textView = root.findViewById(R.id.text_gallery);
galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
textView.setText(s);
}
});
return root;
}
}
it would be great as example to switch from HomePage to GalleryFragment and back
try-->
put this in your mainactivity:-
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_contests) {
//intent to next activity
} else if (id == R.id.nav_rules) {
//just an example
String message = "Text I want to share.";
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(share, "Title of the dialog the system will open"));
} else if (id == R.id.nav_profile) {
///your actions
}
} else if (id == R.id.nav_calendar) {
}
} else if (id == R.id.nav_gallery) {
}
} else if (id == R.id.nav_stats) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Demo
main_activity:
package ijsolutions.appnav;
import android.os.Bundle;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;
import android.view.MenuItem;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.view.Menu;
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);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_home);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_home:
fragment = new Menu1();
//ft.addToBackStack(null);
break;
case R.id.nav_gallery:
fragment = new Menu2();
ft.addToBackStack(null);
break;
case R.id.nav_slideshow:
fragment = new Menu3();
ft.addToBackStack(null);
break;
}
//replacing the fragment
if (fragment != null) {
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}}
Menu1
public class Menu1 extends Fragment {
public Menu1() {
// 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_menu1, container, false);
}
}
xml of menu1
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Menu1"
android:background="#68a">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/Home"
android:layout_marginLeft="60dp"
android:textSize="50dp"
/>
so am not puting the rest menus as it is same
activitymain xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
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"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
activity_main_drawer
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_menu_camera"
android:title="#string/menu_home" />
<item
android:id="#+id/nav_gallery"
android:icon="#drawable/ic_menu_gallery"
android:title="#string/menu_gallery" />
<item
android:id="#+id/nav_slideshow"
android:icon="#drawable/ic_menu_slideshow"
android:title="#string/menu_slideshow" />
<item
android:id="#+id/nav_tools"
android:icon="#drawable/ic_menu_manage"
android:title="#string/menu_tools" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_menu_share"
android:title="#string/menu_share" />
<item
android:id="#+id/nav_send"
android:icon="#drawable/ic_menu_send"
android:title="#string/menu_send" />
</menu>
</item>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
</menu>
content_main:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="#layout/app_bar_main">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
app_bar_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="#layout/content_main" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Add in you activity. It works
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_home) {
}else if (id == R.id.nav_logout) {
logOut(HomePage.this, "Logout due to nav. logout");
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}

How to solve navigation bar with navigation bottom problem

My question is that I was trying to make a simple app, and I used both navigation bar and bottom navigation in the same activity, but I am having a simple problem, such as When I run the app, I'm in home fragment, but when I drag the navigation bar and click on movies, it goes into movies fragment, and my movies item got checked, but the problem is when I again click on home in bottom navigation menu than in my navigation menu the movies item still become checked. Please tell how should I do that if I click on home in bottom navigation then in my navigation bar my movies item become unchecked.
Hope you will understand my problem
Here is my code:-
MainActivity : -
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private FirebaseAuth mAuth;
private DrawerLayout drawerLayout;
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_search:
selectedFragment = new SearchFragment();
break;
case R.id.nav_features:
selectedFragment = new FeaturesFragment();
break;
case R.id.nav_myMusic:
selectedFragment = new MyMusicFragment();
break;
}
assert selectedFragment != null;
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
return true;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
drawerLayout = findViewById(R.id.Drawyer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
mAuth = FirebaseAuth.getInstance();
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
Fragment selections = null;
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser currentuser;
currentuser = mAuth.getCurrentUser();
if (currentuser == null) {
SendUserToSelectTypeActivity();
}
}
private void SendUserToSelectTypeActivity() {
Intent testintent = new Intent(MainActivity.this, Selecttype.class);
testintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(testintent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
finish();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_Movies:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new MoviesFragment()).commit();
break;
case R.id.nav_log_out:
SendUserToSelectTypeActivity();
mAuth.signOut();
break;
case R.id.nav_live:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container
, new LiveVideosFragment()).commit();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
HomeFragment : -
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home , container , false);
}
}
navigation menu:-
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
<item
android:id="#+id/nav_Movies"
android:icon="#drawable/ic_movie"
android:title="Movies" />
<item
android:id="#+id/nav_live"
android:icon="#drawable/ic_movie"
android:title="Live Videos" />
</group>
<item android:title="Communicate">
<menu>
<item
android:id="#+id/nav_share"
android:icon="#drawable/ic_share_black_24dp"
android:title="Share" />
<item
android:id="#+id/nav_contact"
android:icon="#drawable/ic_report_black_24dp"
android:title="Report us" />
<item
android:id="#+id/nav_log_out"
android:icon="#drawable/ic_arrow_back_black_24dp"
android:title="Log Out" />
</menu>
</item>
</menu>
activity main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/Drawyer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:fitsSystemWindows="true"
tools:context=".MainClasses.MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/bottom_navigation">
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#color/design_default_color_primary_dark"
app:itemIconTint="#color/White"
app:itemTextColor="#color/White"
app:menu="#menu/bottom_navigation_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="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/naviation_menu_main"
>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
Please answer me if you found the solution
Make one file in drawable like "bottom_icon_color.xml"
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="#color/red" />
<item android:state_checked="false" android:color="#color/lightgray" />
</selector>
Then apply it to your bottom navigation
app:itemIconTint="#drawable/bottom_icon_color"
app:itemTextColor="#drawable/bottom_icon_color"
According to the problem you had mentioned in the question
you have to first store the previously clicked MenuItem and then make it as unchecked by using setCheckable(false) of MenuItem.
I'm assuming that the rest of all the functions are working, for example, check the item of NavigationView when the bottom navigation item is selected.
In your onNavigationItemSelected store, the clicked MenuItem in one variable say prevMenuItem of type MenuItem.
Now in your BottomNavigationView.OnNavigationItemSelectedListener() make this prevMenuItem as unchecked using this.
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.getMenu().findItem(previousMenuItem.getId()).setCheckable(false);

Need some help bottom menu

Hello guys so i'm watching a tutorial and not sure if i'm doing this right!
So i have an app like this picture
SideBar
and i want to add a bottom menu for my event fragment
Bottom menu
so what i made until now
create a folder
app>res>menu
bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/bot_home"
android:icon="#drawable/ic_home"
android:title="Home" />
<item
android:id="#+id/bot_favorites"
android:icon="#drawable/ic_favorite"
android:title="Favorites" />
<item
android:id="#+id/bot_search"
android:icon="#drawable/ic_search"
android:title="Search" />
</menu>
then i have create all this fragments (NOT SURE if i made this correct)
app>res>menu
Layout
I create the fragment_home.xml, fragment_favorites.xml and fragment_search.xml
they all have this code inside, the difference is only the android:text and android:background
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_red_light">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home"
android:textSize="30sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
them i create a java class for each one
app>java>com.example.readytogo
so all of this 3 java class dat i create have this code the only thing its change is the fragment_home, fragment_favorites and fragment_search
HomeFragment.java
package com.example.readytogo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class HomeFragment extends Fragment {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home,container,false);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<FrameLayout
android:id="#+id/fragment_container"
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="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:menu="#menu/bottom_navigation"
android:background="?android:attr/windowBackground"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:id="#+id/toolbar"
android:theme="#style/Theme.AppCompat.DayNight.DarkActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:elevation="4dp"/>
<androidx.fragment.app.FragmentTabHost
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:id="#+id/nav_view"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu"/>
</androidx.drawerlayout.widget.DrawerLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView =findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
navigationView.setCheckedItem(R.id.nav_profile);
BottomNavigationView bottomNav = findViewById(R.id.bottom_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment seletedFragment = null;
switch (menuItem.getItemId()) {
case R.id.bot_home:
seletedFragment = new HomeFragment();
break;
case R.id.bot_favorites:
seletedFragment = new FavoritesFragment();
break;
case R.id.bot_search:
seletedFragment = new SearchFragment();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
seletedFragment).commit();
return true;
}
};
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nav_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
break;
case R.id.nav_events:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new EventsFragment()).commit();
break;
case R.id.nav_aboutus:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new AboutUsFragment()).commit();
break;
case R.id.nav_faq:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FAQFragment()).commit();
break;
case R.id.nav_settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SettingsFragment()).commit();
break;
case R.id.nav_share:
Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
break;
case R.id.nav_logout:
Toast.makeText(this, "Logout", Toast.LENGTH_SHORT).show();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed(){
if (drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
when i run the app i only got this my sidebar gone and only get this and nothing happen when i click on the home favorites and search
I'm new in android,
I really appreciate all your help! thank you

Change color of NavigationDrawer click color [duplicate]

This question already has answers here:
Change background color of selected item on a ListView
(17 answers)
Closed 8 years ago.
I would like to know how to change the list item click color of the NavigationDrawer as shown by the arrow in the image from blue to for instance red.
My second question is that I would like to add a logo (image), where upon click would direct user to the MainActivity activity at the actionbar (top bar), and below is the activity code that calls the ActionBarActivity.
public class MainActivity extends ActionBarActivity {
private String[] mOptionMenu;
private DrawerLayout mDrawerLayout;
private RelativeLayout mDrawerRelativeLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mTitleSection;
private CharSequence mTitleApp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mOptionMenu = new String[] { "Opción 1", "Opción 2", "Opción 3" };
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerRelativeLayout = (RelativeLayout)
findViewById(R.id.left_drawer);
mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
mOptionMenu));
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FirstFragment();
break;
case 1:
fragment = new SecondFragment();
break;
case 2:
fragment = new ThirdFragment();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mTitleSection = mOptionMenu[position];
getSupportActionBar().setTitle(mTitleSection);
mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
}
});
mDrawerList.setItemChecked(0, true);
mTitleSection = getTitle();
mTitleApp = getTitle();
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mTitleSection);
ActivityCompat.invalidateOptionsMenu(MainActivity.this);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show();
;
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
Thanks in advance.
On Your first question for Background indicator. it works above API level 11.
navigation_list_background.xml Add your desired colors
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_activated="true" android:drawable="#color/green" />
<item android:state_selected="true" android:drawable="#color/green" />
<item android:state_pressed="true" android:drawable="#color/light_blue" />
<item android:state_focused="true" android:drawable="#color/light_blue" />
<item android:drawable="#color/blue" />
</selector>
Add to your base style :
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:activatedBackgroundIndicator">#drawable/navigation_list_background</item>
</style>
Add the background to your layout ( which is your item you display in the drawer)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="?android:attr/activatedBackgroundIndicator"
android:orientation="horizontal" >
<TextView
android:id="#+id/title"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="8"
android:text="Option 1" />
</LinearLayout>
Hope this works.!!
And to your second question. You can use custom action bar.
customactionbar.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ImageView
android:id="#+id/header_drawer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/drawermenu" />
<TextView
android:id="#+id/header_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
android:text="TEST"
android:textStyle="bold" />
<ImageView
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/button" />
</LinearLayout>
<View
android:id="#+id/actionbarseperator"
android:layout_width="match_parent"
android:layout_height="3dp"
android:background="#color/blue" />
</LinearLayout>
Yourlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<include layout="#layout/actionbar" />
<--Your Layout-->
</LinearLayout>
Add this in your Java before setcontent
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
Add for onclick on the button.
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(this);
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button:
ActivityYouwantToOpen.onOpen(v);
break;
}
}
Its a long post :P
You can use selector to change color of pressed states in your mDrawerList. First of all, create a red color solid drawable shape(say redbg) like this in your res/drawable/redbg.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#android:color/holo_red_dark"/>
</shape>
then create a selector say(listviewbg) in res/drawable/listviewbg.xml like this
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="#drawable/redbg"/>
</selector>
and apply this bg to your mDrawerList in xml
<ListView
android:id="#+id/mDrawerList "
android:layout_width="match_parent"
android:layout_height="match_parent"
android:listSelector="#drawable/listviewbg"
/>

Categories