Using bottom nav bar - java

I am trying to make a bottom navigation bar to navigation bar between activities but I find using fragments very confusing so I tried using but its not working tried to look for something that I can use but I did not find anything online so as people who have experience can I use bottom navigation bar without fragments.
My code:
private BottomNavigationView.OnNavigationItemSelectedListener
mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_dashboard:
Intent intent1 = new Intent(RedirectedsearchActivity.this,
SearchActivity.class);
startActivity(intent1);
return true;
It didn’t work.

You can try the navigation component.
With it, it is much easier to work with fragments.
There are a couple of links to documentation and articles.
Documentation https://developer.android.com/guide/navigation
And tutorial https://www.androidauthority.com/android-navigation-architecture-component-908660/

Try this code and make activity_main layout.. without fragment it not working that time you need each and every activity define bottom navigation.
<?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"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:layout_height="match_parent">
<include
android:id="#+id/amToolbar"
layout="#layout/app_toolbar"
/>
<FrameLayout
android:id="#+id/activity_main_container"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:layout_constraintTop_toBottomOf="#+id/amToolbar"
app:layout_constraintBottom_toTopOf="#id/bottom_navigation"
/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemIconTint="#drawable/bottom_navigation_colors"
app:itemTextColor="#drawable/bottom_navigation_colors"
app:labelVisibilityMode="labeled"
app:layout_constraintBottom_toBottomOf="parent"
app:menu="#menu/bottom_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
after that mainActivity call click event..
// Set action to perform when any menu-item is selected.
bottom_navigation.setOnNavigationItemSelectedListener { item ->
item.isChecked = true
selectFragment(item)
false
}
private fun selectFragment(item: MenuItem?) {
item?.isChecked = true
when (item?.itemId) {
R.id.action_uploadFile -> {
// here define fragment change
}
}
}

Related

Cart badge with bottom navigation view android

I'm building a shop android app which I need to set these items in bottom navigation view (Home, cart, favorites, more)
and I need to set badge on cart to view how many items in cart
I build bottom nav bar successfully but I can't add cart badge on icon.
this is my code in activity which I set menu for nav view.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_products);
Objects.requireNonNull(getSupportActionBar()).hide();
context = this;
tools = Tools.getInstance(context);
prefs = Prefs.getInstance(context);
tools.DisplayLang(prefs.GetLang(),this);
nav = findViewById(R.id.bottom_nav_view);
nav.inflateMenu(R.menu.menu);
nav.setSelectedItemId(R.id.home);
getSupportFragmentManager().beginTransaction().replace(R.id.frag_container,new Home())
.commit();
nav.setOnItemSelectedListener(btm_nav);
}
NavigationBarView.OnItemSelectedListener btm_nav =
new NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.home:
fragment = new Home();
getSupportFragmentManager().beginTransaction().replace(R.id.frag_container,fragment).commit();
break;
case R.id.fav:
fragment = new Favourite();
getSupportFragmentManager().beginTransaction().replace(R.id.frag_container,fragment).commit();
break;
case R.id.cart:
fragment = new Cart();
getSupportFragmentManager().beginTransaction().replace(R.id.frag_container,fragment).commit();
break;
case R.id.more:
PopupMenu menu = new PopupMenu(Products.this,
findViewById(R.id.more));
menu.getMenuInflater().inflate(R.menu.pop_up,menu.getMenu());
tools.setForceShowIcon(menu);
menu.show();
break;
}
return true;
}
};
#menu/menu
<?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/home"
android:title="#string/home"
android:icon="#drawable/home"/>
<item android:id="#+id/cart"
android:title="#string/basket"
android:icon="#drawable/cart"
app:actionLayout="#layout/cart_layout"/>
<item android:id="#+id/fav"
android:title="#string/fav"
android:icon="#drawable/fav"/>
<item android:id="#+id/more"
android:title="#string/more"
android:icon="#drawable/more"/>
</menu>
#layout/cart_layout
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:src="#drawable/cart"
app:layout_constraintEnd_toStartOf="#+id/txt_count"
app:layout_constraintHorizontal_bias="0.458"
app:layout_constraintStart_toStartOf="#+id/txt_count"
app:layout_constraintTop_toTopOf="#+id/txt_count" />
<TextView
android:id="#+id/txt_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="668dp"
android:background="#drawable/cart_badge"
android:gravity="center"
android:padding="3dp"
android:text="0"
android:textColor="#color/white"
android:textSize="10dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.598"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I don't have any errors but my problem is that badge doesn't appear on cart icon. How can I do that ?
If you are using the Material Components library, then there is no need to create an extra layout for your badge, unless you want a custom badge. For adding badge to a menu item, first initialize a BadgeDrawable with your menu item's id. For example:
BadgeDrawable badge = nav.getOrCreateBadge(R.id.cart);
Here, nav is your bottom navigation view and R.id.cart is your menu item's id. After initialization, set the badge to be visible by badge.setVisible(true); and finally set the number on the badge by badge.setNumber(1);. You can even set the badge's background color by badge.setBackgroundColor(getResources().getColor(R.color.red)); and badge's text color by badge.setTextColor(getResources().getColor(R.color.white));. And finally when you want to remove the number just call badge.clearNumber();.

How to close bottom navigation or call another empty activity?

This one activity but i try to close the bottom navigation when the user selected one of the side menu fragment. Example when i click my account the bottom not hide.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nav_account:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new AccountFragment()).commit();
break;
case R.id.nav_support:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new SupportFragment()).commit();
break;
case R.id.nav_aboutus:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new AboutusFragment()).commit();
break;
case R.id.nav_logout:
firebaseAuth.signOut();
startActivity(new Intent(getApplicationContext(),Signin.class));
break;
}
mDrawerlayout.closeDrawer(GravityCompat.START);
return true;
}
I hope that will simple code or maybe add another activity?
This my layout
<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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".sidemenu">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<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"/>
</RelativeLayout>
<com.google.android.material.navigation.NavigationView
app:headerLayout="#layout/header"
android:id="#+id/nav_View"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#color/white"
app:itemTextColor="#color/Black"
app:itemIconTint="#color/gray"
app:menu="#menu/drawermenu"
android:layout_gravity="start">
</com.google.android.material.navigation.NavigationView>
Maybe put some code in navigation or bottom navigation
As your container and BottomNavigation in same activity layout and you are using your container for fragment.
Create one interface
public interface IBottomBarListener{
public void showBottomBar();
public void hideBottomBar()
}
Implement this interface in your activity and override these two methods.
public void showBottomBar(){
// make your bottom bar visibility visible
}
public void hideBottomBar(){
// make your bottom bar visibility gone
}
Now in your fragment declare global variable
public IBottomBarListener listener;
Now in onAttach() method , init your listener
listener = (IBottomBarListener)context
now in onCreateView(), call
listener.hideBottomBar() // this will hide your bottombar
also in onDetach() method, if you want to again make visible your bottombar,
onDetach(){
listener.showBottomBar() // this will show your bottombar
}
This is basically showing/hiding your bottombar from your fragment. So do same in all fragment from where you want to perform this action.

onNavigationItemSelected not being called for Bottom Navigation Bar

I'm trying to implement a bottom nav bar that changes fragments when the nav items are clicked. However, when I click on the nav bar items, the fragments don't change. Using log.d, I noticed onNavigationItemSelected is not being called. How do I fix this?
To note, the startFeedFragment, startScheduleFragment, & startSettingsFragmentare implemented the same way and they work for the buttons in the toolbar. I also referenced this tutorial and this question for help.
MainActivity.java
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setUpRecycler();
startFeedFragment();
BottomNavigationView bottomNavBar = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavBar.bringToFront();
bottomNavBar.setOnNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Log.d("NAV BAR", "onNavigationItemSelected hit");
switch (item.getItemId()) {
case R.id.feedMenu:
startFeedFragment();
Log.d("NAV BAR", "feed");
break;
case R.id.myScheduleMenu:
startScheduleFragment();
Log.d("NAV BAR", "schedule");
break;
case R.id.settingsMenu:
startSettingsFragment();
Log.d("NAV BAR", "settings lol");
break;
default:
Log.d("NAV BAR", "false");
return false;
}
return true;
}
/**
* Switches out the fragment for {#link FeedFragment} and sets an appropriate title. startScheduleFragmens & startSettingsFragment are implemented the same way
*/
private void startFeedFragment()
{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, new FeedFragment());
transaction.commit();
getSupportActionBar().setTitle(R.string.title_fragment_feed);
}
}
Snippet from xml file
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemBackground="#android:color/white"
app:itemIconTint="#color/colorPrimaryDark"
app:itemTextColor="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_nav"
android:elevation="8dp"/>
</android.support.constraint.ConstraintLayout>
</android.support.design.widget.CoordinatorLayout>
Solved! It was because I had set the buttons in the menu to android:enabled="false". That meant they couldn't be pressed, which is why onNavigationItemSelected wasn't being called. I set all buttons to android:enabled="true" to fix this.
Correct code for bottom_nav.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/bottom_nav_my_schedule"
android:title="#string/menu_my_schedule"
android:icon="#drawable/ic_event_available_white_24dp"
android:enabled="true"/> <!--make sure enabled is set to true!-->
<item android:id="#+id/bottom_nav_feed"
android:title="#string/menu_feed"
android:icon="#drawable/ic_view_list_white_24dp"
android:enabled="true" /> <!--make sure enabled is set to true!-->
<item android:id="#+id/bottom_nav_settings"
android:title="#string/menu_settings"
android:icon="#drawable/ic_settings_white_24dp"
android:enabled="true"/> <!--make sure enabled is set to true!-->
</menu>
As for me the problem was when my activity main layout was LinearLayout, so I've solved it by changing it to RelativeLayout, I have absolutely no thoughts why it's working, because RelativeLayout layouts reply only for elements location, not its view or something else, but it's working.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemBackground="#drawable/selector"
android:background="#color/white"
app:menu="#menu/menu_bottom"
app:itemIconTint="#drawable/menu_trainings"
app:labelVisibilityMode="unlabeled"
/>
</RelativeLayout>

How to implement a back arrow in fragment

I have a nav drawer which in its first fragment i have a news page where the user clicks a button to see the whole news, and at that moment it enters another fragment.
I want to know how I implement an arrow to return to the previous fragment instead of the icon that opens the Navigation Drawer.
I've never worked with this before, I have no idea.
This is my Toolbar in MainActivity
appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
//toolbar title
toolbar.setTitle(null);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
// Toolbar logo
logoToolbar = (ImageView) findViewById(R.id.logoToolbar);
logoToolbar.setImageResource(R.drawable.newstoolbar);
When the user click in "Read More" in the MainFragment
newsMore.get(0).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
newsFrag1 newsFragment1 = new newsFrag1();
ft.replace(R.id.fragment_container, newsFragment1);
ft.commit();
}
});
And then it goes to newsFrag1, which I want to have the back arrow
My Toolbar XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="studio.com.archeagemanager.MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
app:elevation="0dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="?attr/colorPrimary"
android:gravity="center_vertical"
android:minHeight="56dp"
android:weightSum="1"
app:popupTheme="#style/AppTheme.PopupOverlay">
<ImageView
android:id="#+id/logoToolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="56dp">
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
Fragments don't normally intercept back/up presses. That is something that's normally done at the activity level. The reasoning behind that is because you can have multiple fragments on screen at the same time... so which one handles the back press first?
To handle it in your activity, consider keeping track of your before and after state. Let's use the fragment count as an example state:
#Override
public void onBackPressed() {
// for every back press, if there is a fragment to remove, then remove it first
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
return;
}
super.onBackPressed();
}
You also need to make sure you add your original fragment transaction to the backstack:
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
newsFrag1 newsFragment1 = new newsFrag1();
ft.replace(R.id.fragment_container, newsFragment1);
ft.addToBackStack();
ft.commit();
Edit: I think from your xml what you're asking for is UP navigation, not BACK navigation. If that is the case, then you still need to leverage the backstack but all the work needs to be done by the parent activity (because the activity owns the toolbar)
getSupportFragmentManager()
.addOnBackStackChangedListener(new OnBackStackChangedListener(){
#Override
public void onBackStackChanged() {
updateToolbarUp();
}
});
public void updateToolbarUp(){
boolean showUp = getSupportFragmentManager().getBackStackEntryCount() > 0;
getSupportActionBar().setDisplayHomeAsUpEnabled(showUp);
}
Then override the up press to simply pop the backstack:
#Override
public boolean onSupportNavigateUp() {
getSupportFragmentManager().popBackStack();
return true;
}

How to Set Icon to display on the far right in Java

getSupportActionBar().setLogo(R.drawable.addicon);
The code above seems to place my Icon in the Centre . I would like to place to the far right and make it clickable as well . At the moment it the image for the icon is in the project files as a drawable I have not included it in any xml files.
You can set android:layoutDirection="rtl" in your toolbar xml for place it to right and
set below code for clickable :
getSupportActionbar().setDisplayHomeAsUpEnabled(true);
and :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//Do stuff
return true;
default:
return super.onOptionsItemSelected(item);
}
}
There are 2 approaches for doing that.
Option Menus
Creating custom toolbar.
With Option Menus
create main.xml under res/menu.
<menu 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"
tools:context="com.ioa.MainActivity" >
<item
android:id="#+id/action_addition"
android:icon="#drawable/addicon"
android:orderInCategory="100"
android:title="Addition"
app:showAsAction="always"/>
</menu>
and inside your activity create menu like,
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
you can perform Action on particular menu item.
#Override
public boolean onOptionsItemSelected(MenuItem Item) {
if (Item.getItemId() == R.id.action_addition) {
// perform action
}
return super.onOptionsItemSelected(paramMenuItem);
}
With custom toolbar
Create your ToolBar like this,
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ColorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/add"
android:layout_width="46dp"
android:layout_height="46dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="4dp"
android:clickable="true"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
and now you can perform click event of particular ImageView.
ImageView add = (ImageView) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do work.
}
});
happy Coding.
You Need 3 Things:
A Custom Toolbar Layout
Include the toolbar in your activity
Set the Logo to the toolbar
Create new Resource Layout:
include_toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="?attr/colorPrimaryDark"
android:id="#+id/include_toolbar"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
Change Your Activity File: MainActivity.java
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar)findViewById(R.id.include_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.mipmap_ic_launcher);
}
}
And here's the styles.xml:
<!-- language: xml-->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
</resources>

Categories