How to enable state of bottom navigation, if i go back? - java

When I press back key then the color of bottom navigation not change but my fragment get change. I want to change both at a time. i.e. when I go back then fragment should change with bottom navigation icon.
Here is my current code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private FrameLayout mMainFrame;
Fragment homeFragment = new HomeFragment();
Fragment trendingFragment = new TrendingFragment();
Fragment latestFragment = new LatestFragment();
Fragment inboxFragment= new InboxFragment();
Fragment libraryFragment = new LibraryFragment();
// Adding acion on botom navigation icon basically adding Fragment Action
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.bottom_navigation_home:
setFragment(homeFragment);
return true;
case R.id.bottom_navigation_trending:
setFragment(trendingFragment);
return true;
case R.id.bottom_navigation_latest:
setFragment(latestFragment);
return true;
case R.id.bottom_navigation_inbox:
setFragment(inboxFragment);
return true;
case R.id.bottom_navigation_library:
setFragment(libraryFragment);
return true;
default:
return false;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Decleration Connecting Java To xml
mMainFrame = (FrameLayout) findViewById(R.id.main_container);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.bottom_navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
setFragment(homeFragment); // Start Home Fregment first
}
#Override
public void onBackPressed(){
if (getSupportFragmentManager().getBackStackEntryCount() == 1){
finish();
}
else {
super.onBackPressed();
}
}
//Declear Method
private void setFragment(Fragment fragment) {
// Set fragment in frame layout
String backStateName = fragment.getClass().getName();
String fragmentTag = backStateName;
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);
if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null){ //fragment not in back stack, create it.
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.main_container, fragment, fragmentTag);
ft.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
ft.addToBackStack(backStateName);
ft.commit();
}
}
}
bottom_nav_color_selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/colorPrimary" android:state_checked="true"/>
<item android:color="#color/colorIcon" android:state_checked="false"/>
</selector>
BottomNavigationView in MainActivity.xml
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="#color/colorWhite"
android:clickable="true"
android:focusable="true"
app:itemIconSize="25dp"
app:itemIconTint="#color/bottom_nav_color_selector"
app:itemTextAppearanceActive="#style/BottomNavigationView.Active"
app:itemTextAppearanceInactive="#style/BottomNavigationView"
app:itemTextColor="#color/bottom_nav_color_selector"
app:labelVisibilityMode="labeled"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_navigation" />

hi try this set itemIconTint and itemTextColor a color selector xml of your specific colors
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#color/Black"
app:itemBackground="#color/White"
app:itemIconTint="#color/nav_selector"
app:itemTextColor="#color/nav_selector"
app:menu="#menu/nav_menu" />
here is nav_selector.xml put this file in res->color folder
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/OrangeBrown" android:state_checked="true" />
<item android:color="#color/OrangeBrown" android:state_enabled="true" android:state_pressed="true" />
<item android:color="#color/BlackishGray" />
</selector>
and if you want to click on specific tab you can do that with below code
View view = bottomNavigationView.findViewById(R.id.nav_home);
view.performClick();

Here is ans. to handle bottom navigation perfectly with back pressed and active Navigation button.
public class MainActivity extends AppCompatActivity {
private Fragment homeFragment = new HomeFragment();
private Fragment trendingFragment = new TrendingFragment();
private Fragment latestFragment = new LatestFragment();
private Fragment inboxFragment = new InboxFragment();
private Fragment libraryFragment = new LibraryFragment();
private BottomNavigationView navigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigation = findViewById(R.id.bottom_navigation);
}
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 1) {
finish();
} else {
super.onBackPressed();
if (homeFragment.isResumed())
navigation.setSelectedItemId(R.id.bottom_navigation_home);
else if (trendingFragment.isResumed())
navigation.setSelectedItemId(R.id.bottom_navigation_trending);
else if (latestFragment.isResumed())
navigation.setSelectedItemId(R.id.bottom_navigation_latest);
else if (inboxFragment.isResumed())
navigation.setSelectedItemId(R.id.bottom_navigation_inbox);
else if (libraryFragment.isResumed())
navigation.setSelectedItemId(R.id.bottom_navigation_library);
}
}

Related

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);

navigation drawer not showing properly

I am developing news app and I have implemented navigation drawer
using following link but when I run the code app showing empty white
screen.
below my MainActivity.java class
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawer;
private Toolbar toolbar;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Inflate the header view at runtime
View headerLayout = nvDrawer.inflateHeaderView(R.layout.nav_header);
// We can now look up items within the header if needed
#SuppressLint("ResourceType") ImageView ivHeaderPhoto = headerLayout.findViewById(R.drawable.ic_sportnews);
setupDrawerContent(nvDrawer);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
mDrawer.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
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 = null;
switch (menuItem.getItemId()) {
case R.id.bbcsports_fragment:
fragmentClass = BBCSportFragment.class;
break;
case R.id.talksports_fragment:
fragmentClass = TalkSportsFragment.class;
break; case R.id.foxsports_fragment:
fragmentClass = FoxSportsFragment.class;
break;
default:
}
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.flContent, 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
mDrawer.closeDrawers();
}
}
below my activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
app:headerLayout="#layout/nav_header"
app:menu="#menu/navigation_menu" />
</android.support.v4.widget.DrawerLayout>
below my Fragment class
public class BBCSportFragment extends Fragment {
public List<Article> articleList = new ArrayList<Article>();
#BindView(R.id.recycler_view)
RecyclerView recyclerView;
private SportNews sportNews;
private ArticleAdapter articleAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_bbcsport, container, false);
ButterKnife.bind(this, view);
SportInterface sportInterface = SportClient.getApiService();
Call<SportNews> call = sportInterface.getArticles();
call.enqueue(new Callback<SportNews>() {
#Override
public void onResponse(Call<SportNews> call, Response<SportNews> response) {
sportNews = response.body();
if (sportNews != null && sportNews.getArticles() != null) {
articleList.addAll(sportNews.getArticles());
}
articleAdapter = new ArticleAdapter(articleList, sportNews);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(articleAdapter);
}
#Override
public void onFailure(Call<SportNews> call, Throwable t) {
}
});
return view;
}
}

How can I implement the bottom navigation bar into an app for android?

Here is a piece of Java code.
The Android app stops when I tap on an item in the BottomNavigationView, it should open a fragment.
public class MainActivity extends AppCompatActivity {
private BottomNavigationView bottomNavigationView;
private BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths:
switch (item.getItemId()) {
case R.id.item0:
transaction.replace(R.id.content, new Item0_Fragment()).commit();
return true;
case R.id.item1:
transaction.replace(R.id.content, new Item1_Fragment()).commit();
return true;
case R.id.item2:
transaction.replace(R.id.content, new Item2_Fragment()).commit();
return true;
case R.id.item3:
transaction.replace(R.id.content, new Item3_Fragment()).commit();
return true;
}
return false;
}
});
}
First, you did declares two times the BottomNavigationView. In second, you not writed the complete code, leaving aside parts that may be important. However I did write a code for this. Try read my code or just copy and paste. You just need create your fragments, if needs help to do this let me know.
MainActivity.java
public class MainActivity extends AppCompatActivity {
List<Fragment> fragmentList;
MyAdapter myAdapter;
ViewPager viewPager;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG,"onCreate()");
fragmentList = new ArrayList<>();
fragmentList.add(new Fragment1());
fragmentList.add(new Fragment2());
bottomNavigationView = findViewById(R.id.bottomNavigationView);
viewPager = findViewById(R.id.viewPagerAppActivity);
myAdapter = new MyAdapter(getSupportFragmentManager());
viewPager.setAdapter(myAdapter);
viewPager.setCurrentItem(0);
bottomNavigationView.setOnNavigationItemSelectedListener(botNavViewItemSelectedListener());
}
public BottomNavigationView.OnNavigationItemSelectedListener botNavViewItemSelectedListener() {
return new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.itemFragment1:
viewPager.setCurrentItem(0);
break;
case R.id.itemFragment2:
viewPager.setCurrentItem(1);
break;
}
return true;
}
};
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
}
}
activity_main.xml
<android.support.constraint.ConstraintLayout android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v4.view.ViewPager
android:id="#+id/viewPagerAppActivity"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#id/bottomNavigationView"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginBottom="0dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="0dp"
app:layout_constraintVertical_bias="1.0" />
<android.support.design.widget.BottomNavigationView
app:menu="#menu/menu_bottom"
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemBackground="#color/colorPrimary"
app:itemIconTint="#drawable/bottom_bar_item_selector"
app:itemTextColor="#drawable/bottom_bar_item_selector"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
</android.support.constraint.ConstraintLayout>
menu_bottom.xml to populate my menu of navigation
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/itemFragment1" android:title="Frag1" android:enabled="true" app:showAsAction="always|withText" android:icon="#mipmap/ic_launcher"/>
<item android:id="#+id/itemFragment2" android:title="Frag2" android:enabled="true" app:showAsAction="always|withText" android:icon="#mipmap/ic_launcher"/>
</menu>
*For fragment click this http://www.truiton.com/2017/01/android-bottom-navigation-bar-example/
*For activities
Following code makes the bottom navigation for activites(same feel as to fragment)
STEP 1: Create a BaseActivity and name it as BaseActivity
BaseActivity.java
public abstract class BaseActivity extends AppCompatActivity implements
BottomNavigationView.OnNavigationItemSelectedListener{
protected BottomNavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getContentViewId());
navigationView = findViewById(R.id.navigation);
navigationView.setOnNavigationItemSelectedListener(this);
BottomNavigationViewHelper.disableShiftMode(navigationView);
}
#Override
protected void onStart() {
super.onStart();
updateNavigationBarState();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menuBuilding) {
startActivity(new Intent(this, ActivityA.class));
} else if (itemId == R.id.menuChat) {
startActivity(new Intent(this, ActivityB.class));
} else if (itemId == R.id.menuProfile) {
startActivity(new Intent(this, ActivityC.class));
}
overridePendingTransition(0, 0);
finish();
return true;
}
private void updateNavigationBarState() {
int actionId = getNavigationMenuItemId();
selectBottomNavigationBarItem(actionId);
}
void selectBottomNavigationBarItem(int itemId) {
Menu menu = navigationView.getMenu();
for (int i = 0, size = menu.size(); i < size; i++) {
MenuItem item = menu.getItem(i);
boolean shouldBeChecked = item.getItemId() == itemId;
if (shouldBeChecked) {
item.setChecked(true);
break;
}
}
}
abstract int getContentViewId();
abstract int getNavigationMenuItemId();
}
STEP 2:
Create a child activity and name it as ActivityA and copy paste the following code
ActivityA.java
public class ActivityA extends BaseActivity implements {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
int getContentViewId() {
return R.layout.activity_a_layout;
}
#Override
int getNavigationMenuItemId() {
return R.id.menuBuilding;
}
}
Similary create ActivityB.java and ActivityC.java .Make both classes similar to ActivityA.java.But the different is ActivityA.java returns
#Override
int getNavigationMenuItemId() {
return R.id.menuBuilding;
}
and
ActivityB.java returns
#Override
int getNavigationMenuItemId() {
return R.id.menuChat;
}
and
ActivityC.java returns`
#Override
int getNavigationMenuItemId() {
return R.id.menuProfile;
}
Also create layout for two java class and copy paste the activity_a_layout.xml code to both layouts of ActivityB.java and ActivityC.java
STEP 3 : Create a layout named activity_a_layout and copy paste the following code
'activity_a_layout.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/toolbar"
android:background="#android:color/white">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Coming soon..."
android:textSize="19sp"
android:textStyle="bold"
android:layout_centerInParent="true"/>
</RelativeLayout>
<include
android:id="#+id/navigation"
layout="#layout/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" />
</RelativeLayout>
STEP 4:
Create a layout named bottom_navigation and copy pase the following code
bottom_navigation.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.BottomNavigationView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/dark_grey"
app:itemIconTint="#drawable/nav_item_menu_selector"
app:itemTextColor="#drawable/nav_item_menu_selector"
app:menu="#menu/bottom_nav_items" />
STEP 5: Create a menu folder inside res and create a file named bottom_nav_items inside menu and copy paste the below code
bottom_nav_items.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menuChat"
android:icon="#drawable/ic_chat"
android:title="Chat" />
<item
android:id="#+id/menuBuilding"
android:icon="#drawable/ic_building_white"
android:title="Company" />
<item
android:id="#+id/menuProfile"
android:icon="#drawable/menu_item_profile"
android:title="Profile"
app:itemTextColor="#android:color/transparent" />
</menu>
**Dont forgot to declare ActivityA.java,ActivityB.java and ActivityC.java in manifest
HAPPY CODING

Bottom nav view fragment NullPointerException

In my one of my fragments I have a toggle button in the xml:
<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="com.stefan.findage.piano">
<!-- TODO: Update blank fragment layout -->
<ToggleButton
android:id="#+id/metronome"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton" />
</FrameLayout>
And
toggleButton = (ToggleButton) getView().findViewById(R.id.metronome);
But when trying to open the fragment it crashes and the logcat shows that it was a
java.lang.NullPointerException:Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
Here's the Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottomView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.moosic:
rhythm fragmentone = new rhythm();
android.support.v4.app.FragmentTransaction fragmentTransaction3 = getSupportFragmentManager().beginTransaction();
fragmentTransaction3.replace(R.id.frame, fragmentone, "rhythm");
fragmentTransaction3.commit();
return true;
case R.id.call:
intervals fragmenttwo = new intervals();
android.support.v4.app.FragmentTransaction fragmentTransaction2 = getSupportFragmentManager().beginTransaction();
fragmentTransaction2.replace(R.id.frame, fragmenttwo, "intervals");
fragmentTransaction2.commit();
return true;
case R.id.thinga:
piano fragmentthree = new piano();
android.support.v4.app.FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.frame, fragmentthree, "piano");
fragmentTransaction1.commit();
return true;
}
return false;
}
});
}
}
getView() might be returning null. Use the below code to reference the toggle button
View view = inflater.inflate(R.layout.fragmentlayout, container, false);
toggleButton = (ToggleButton) view.findViewById(R.id.metronome);

Toolbar doesn't work with navigation drawer and multiple activities

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

Categories