I'm trying to add a BottomNavigationView in my project but don't show up when i run the project.
I'd like to put this on several activities, aswell as Toolbar so i created a class that initialize both of them and extends AppCompatActivity so that my activies using the Toolbar or the BottomNavigationView just have to extends this activity and call the method that initialize it (i don't know if this is the right method to use, if no please tell me). So this work with my Toolbar, but my BottomNavigationView isn't showing up.
This is my NavigationActivity i talked about :
public abstract class NavigationActivity extends AppCompatActivity {
private Toolbar mToolbar;
private BottomNavigationView mNavigationView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void initNavigation(int navigationId) {
mNavigationView = (BottomNavigationView) findViewById(navigationId);
mNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.navigation_entrainements:
startActivity(new Intent(getBaseContext(),MenuEntrainementsActivity.class));
break;
case R.id.navigation_nutrition:
startActivity(new Intent(getBaseContext(),NutritionActivity.class));
break;
case R.id.navigation_statistiques:
startActivity(new Intent(getBaseContext(),StatistiquesActivity.class));
break;
}
return true;
}
});
}
public void initToolbar(int toolbarId) {
mToolbar = (Toolbar) findViewById(toolbarId);
mToolbar.setNavigationIcon(R.drawable.baseline_arrow_back_black_18dp);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
mToolbar.setNavigationOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.btnHome :
startActivity(new Intent(this,MainActivity.class));
return true;
case R.id.btnProfil :
startActivity(new Intent(this,ProfilActivity.class));
return true;
default :
return super.onOptionsItemSelected(item);
}
}
}
and an exemple of how i'm using it in others activities :
initNavigation(R.id.navigation);
initToolbar(R.id.toolbar);
this is how i implement the BottomNavigationView in my XML files :
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="?android:attr/windowBackground"
app:menu="#menu/navigation" />
if you need anything else just ask,
thanks for your help :)
(sorry if i made mistakes i'm not great in english)
I Use this from outside of onCreate mothod.
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment;
switch (item.getItemId()) {
case R.id.btnHome :
startActivity(new Intent(this,MainActivity.class));
return true;
case R.id.btnProfil :
startActivity(new Intent(this,ProfilActivity.class));
return true;
default :
startActivity(new Intent(this,MainActivity.class));
return true;
}
}
};
Related
home fragment always on screen.i cant solve it.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(this);
bottomNavigationView.setSelectedItemId(R.id.homeFragment)
}
/*#Override
protected void onStart() {
if (currentUser==null){
Intent welcomeIntent= new Intent(MainActivity.this,WelcomeActivity.class);
startActivity(welcomeIntent);
finish();
}
super.onStart();
}*/
homeFragment homeFragment = new homeFragment();
notificationFragment notificationFragment = new notificationFragment();
todolistFragment todolistFragment = new todolistFragment();
profileFragment profileFragment = new profileFragment();
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.homeFragment:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, homeFragment).commit();
return true;
case R.id.notificationFragment:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, notificationFragment).commit();
return true;
case R.id.todolistFragment:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, todolistFragment).commit();
return true;
case R.id.profileFragment:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, profileFragment).commit();
return true;
}
return false;
}
}
on home fragment it doubles.background texts are doesn't disappear.how can i solve it.what is the problem.i am using android studio with java
1
2
these are the screen shots.main text view always appears
I'm making a navigation drawer that slides into the screen. I did this with this code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/home" android:title="Home"></item>
<item android:id="#+id/change_event" android:title="Change Event"></item>
<item android:id="#+id/FAQ" android:title="FAQ"></item>
<item android:id="#+id/map" android:title="Map"></item>
<item android:id="#+id/Schedule" android:title="Schedule"></item>
</menu>
Now in the MainActivity.Java, I'm trying to switch between activities with the OnOptionsItemSelected method. I'm trying this with this code.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.home){
Intent intent = new Intent(MainActivity.this, Home.class);
startActivity(intent);
}
return true;
}
What I want this code to do is when if you open the slide menu and click on the home item, the activity home has to start. This is not working, and I have no idea what I am doing wrong.
You have to add onCreateOptionsMenu
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_menu_file_name, menu);
return true;
}
Updated:
NavigationDrawer class
public class MainActivityNew extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#BindView(R.id.toolbar)
Toolbar toolbar;
#BindView(R.id.nav_view)
NavigationView navView;
#BindView(R.id.drawer_layout)
DrawerLayout drawerLayout;
public static final String TAG_HOME = "Dashboard";
public static final String TAG_TEMP = "Temperature";
public static String CURRENT_TAG = TAG_HOME;
public static int navItemIndex = 0;
public Fragment fragment;
private Fragment sendFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_new);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
if (savedInstanceState != null) {
fragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
} else {
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
loadHomeFragment();
}
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
navView.setNavigationItemSelectedListener(this);
}
private void loadHomeFragment() {
selectNavMenu();
if (getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null) {
drawerLayout.closeDrawers();
return;
} else {
fragment = getHomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
fragmentTransaction.commit();
drawerLayout.closeDrawers();
}
}
private Fragment getHomeFragment() {
switch (navItemIndex) {
case 0:
sendFragment = new HomeFragment();
break;
case 1:
sendFragment = new TemperatureFragment();
break;
default:
sendFragment = new TemperatureFragment();
}
return sendFragment;
}
private void selectNavMenu() {
navView.getMenu().getItem(navItemIndex).setChecked(true);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
return;
}
super.onBackPressed();
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.home:
navItemIndex = 0;
CURRENT_TAG = TAG_HOME;
break;
case R.id.temperrature_sensor:
navItemIndex = 1;
CURRENT_TAG = TAG_TEMP;
break;
default:
navItemIndex = 0;
}
if (menuItem.isChecked()) {
menuItem.setChecked(false);
} else {
menuItem.setChecked(true);
}
menuItem.setChecked(true);
loadHomeFragment();
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
getSupportFragmentManager().putFragment(outState, "myFragmentName", fragment);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
}
}
So I started a new project and implemented BottomNavigationView, I made a class helper, BottomNavigationViewHelper so that the buttons stay where they are supposed to, everything is working perfectly except that the buttons in the navigationview have to be clicked twice insted of working on single click. If I do a single click on the button it will just highlight it and then I have to click it again to access the class/xml.
This is the code for the Helper Class
public class BottomNavigationViewHelper {
#SuppressLint("RestrictedApi")
public static void disableShiftMode(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
try {
Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode");
shiftingMode.setAccessible(true);
shiftingMode.setBoolean(menuView, false);
shiftingMode.setAccessible(false);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i);
//noinspection RestrictedApi
item.setShiftingMode(false);
// set once again checked value, so view will be updated
//noinspection RestrictedApi
item.setChecked(item.getItemData().isChecked());
}
} catch (NoSuchFieldException e) {
Log.e("BNVHelper", "Unable to get shift mode field", e);
} catch (IllegalAccessException e) {
Log.e("BNVHelper", "Unable to change value of shift mode", e);
}
}
public static void enableNavigation(final Context context, BottomNavigationView view){
view.setOnNavigationItemReselectedListener(new BottomNavigationView.OnNavigationItemReselectedListener() {
#Override
public void onNavigationItemReselected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.ic_house:
Intent intent1=new Intent(context, HomeActivity.class); //ACTIVITY_NUM=0
context.startActivity(intent1);
break;
case R.id.ic_search:
Intent intent2=new Intent(context, SearchActivity.class);//ACTIVITY_NUM=1
context.startActivity(intent2);
break;
case R.id.ic_circle:
Intent intent3=new Intent(context, PicActivity.class);//ACTIVITY_NUM=2
context.startActivity(intent3);
break;
case R.id.ic_alert:
Intent intent4=new Intent(context, AlertActivity.class);//ACTIVITY_NUM=3
context.startActivity(intent4);
break;
case R.id.ic_android:
Intent intent5=new Intent(context, ProfileActivity.class);//ACTIVITY_NUM=4
context.startActivity(intent5);
break;
}
}
});
}
}
And this is the profile class
public class ProfileActivity extends AppCompatActivity {
private Context mContext= ProfileActivity.this;
private static final int ACTIVITY_NUM=4;
private static final String TAG ="ProfileActivity";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
setupToolbar();
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
BottomNavigationViewHelper.enableNavigation(mContext, bottomNavigationView);
Menu menu=bottomNavigationView.getMenu();
MenuItem menuItem=menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
Log.d(TAG, "onCreate: started.");
}
private void setupToolbar(){
Toolbar toolbar=(Toolbar) findViewById(R.id.profileToolBar);
setSupportActionBar(toolbar);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Log.d(TAG,"onMenuItemClick:clicked menu item: "+item);
switch (item.getItemId()){
case R.id.profileMenu:
Log.d(TAG,"onMenuItemClick: Navigating to profile preferences.");
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.profile_menu, menu);
return true;
}
}
And finaly the xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentBottom="true">
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/bottomNavViewBar"
android:background="#drawable/white_grey_border_top"
app:menu="#menu/bottom_navigation_menu"
app:itemIconTint="#color/teal"
android:clickable="true"
android:focusable="true">
</android.support.design.widget.BottomNavigationView>
</RelativeLayout>
</merge>
Any help is greatly appreciated.
Be carrefull to register a SelectListener, and not a ReselectListener !
public static void enableNavigation(final Context context, BottomNavigationView view){
view.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public void onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
I have set up a toolbar and added a home navigation button as follows;
Toolbar toolbar;
toolbar = (Toolbar) findViewById(R.id.toolbar_home);
//Setup toolbar
toolbar.setTitle("Home");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
toolbar.setTitleTextColor(getResources().getColor(R.color.icons,null));
}else{
toolbar.setTitleTextColor(getResources().getColor(R.color.icons));
}
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
} else {
Log.w("Home", "toolbar null");
}
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Navigate backwards as android back button
}
});
I want when i press the toolbar backbutton, it navigates backwards following the backstack as the the android backbutton.enter image description here
add this method in activity:
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId() == android.R.id.home){
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
I am following this from long time and not found any issue yet .
HomeFragment : First fragment which getting loaded first time
getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
HomeFragment currentHomeFragment = null;
currentHomeFragment = (HomeFragment) getFragmentManager().findFragmentByTag("HOME_FRAGMENT");
if (currentHomeFragment != null && currentHomeFragment.isVisible()) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
} else {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().popBackStackImmediate();
}
});
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
toggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
}
}
}
});
If you are using android.support.v7.widget.Toolbar add this code to your AppCompatActivity:
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
in your onClick write onBackPressed(); or in manifest
<activity android:name=".XYZActivity"
android:parentActivityName=".MainActivity" />
Setup toolbar in MainActivity onCreate() method.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_home);
toolbar.setTitle("Activity Name");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
Setup back navigation by implementing below method in MainActivity Level.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Works well..
#Rajesh
Inside my SettingsActivity extends AppCompatActivity I have SettingsFragment extends PreferenceFragment. When I try press home-buttion in toolbar it is not working. Here is my code
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/settingsToolbar"
android:layout_width="match_parent"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_height="?android:actionBarSize"
android:background="#color/colorPrimary" />
SettingsActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupToolBar();
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
private void setupToolBar() {
getLayoutInflater().inflate(R.layout.toolbar, (ViewGroup) findViewById(android.R.id.content));
Toolbar toolbar = (Toolbar) findViewById(R.id.settingsToolbar);
setSupportActionBar(toolbar);
setTitle(getResources().getString(R.string.settings));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setFocusable(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
I tried to solve it in such way: remove setNavigationOnClickListener and add this:
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return (super.onOptionsItemSelected(menuItem));
}
It does not help. How can I fix this?
add this line to config your getSupportActionBar:
getSupportActionBar().setHomeButtonEnabled(true);
use both code in your activity like below:
in your setupToolbar method:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Log.d("cek", "home selected");
finish();
}
});
and in your onOptionsItemSelected method:
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);