BottomNavigationView not working on single click - has to be clicked twice - java

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()){

Related

Why does my BottomNavigationView is not showing up?

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

onOptionsItemSelected not working

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

Firebase/DrawerLayout - Logged out for no reason?

I am working on a DrawerLayout, and when I click one of the items to go to a Profile page, it logs me out (I can notice this because I get a NullPointer error for the UserAuth [even though I was authed before clicking this]
Note: I didn't notice this until I tried to modularize my code by adding "initialize" methods and such.
This is the code for the items in the drawerlayout:
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override public boolean onNavigationItemSelected(MenuItem menuItem) {
//If Clicked...then get item and go to associated page
switch(menuItem.getTitle().toString())
{
case "Profile":
Log.i("Profile", menuItem.getTitle().toString());
startActivity(new Intent(HomeActivity.this, ProfileActivity.class));
/*case "Share":
startActivity(new Intent(HomeActivity.this, ProfileActivity.class));
case "Settings":
startActivity(new Intent(HomeActivity.this, ProfileActivity.class)); */
case "Logout":
Log.i("Logout", menuItem.getTitle().toString());
FirebaseAuth.getInstance().signOut();
//startActivity(new Intent(HomeActivity.this, LoginActivity.class));
}
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
For some reason even though I'm clicking the "Profile" item, it goes to both the Case for that, AND for "Logout" as can be seen by the Log statements:
I/Profile: Profile
I/Logout: Profile
And then this leads to the Error:
E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.netgalaxystudios.timeclock/com.netgalaxystudios.timeclock.Activities.ProfileActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.netgalaxystudios.timeclock.Activities.ProfileActivity.onCreate(ProfileActivity.java:70)
ProfileActivity.java (is the activity I am trying to get to by clicking on the ITEM in the menu). It refers to this line, but really the error is coming from HomeActivity as I understand it... ) :
currentUserString = currentUser.getUid().toString();
HomeActivity.java:
public class HomeActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
ImageView menu, closeDrawer;
RelativeLayout navHeader;
//Profile Stuff
DatabaseReference employeesRefPhoto, employeesRefFname, employeesRefLname;
FirebaseDatabase database;
String photoUrl;
ImageView profilePhoto;
FirebaseUser currentUser;
String currentUserString;
TextView nameTV, lnameTV;
TextView businessesTV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_layout);
/////////////////////////
//METHODS
//initViews();
//setupDrawerLayout();
//footerOnClick();
//////////////////////////
menu = (ImageView) findViewById(R.id.menu);
menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
drawerLayout.openDrawer(Gravity.LEFT);
}
});
currentUser = FirebaseAuth.getInstance().getCurrentUser();
currentUserString = currentUser.getUid().toString();
setupDrawerLayout();
//https://stackoverflow.com/questions/37163579/null-pointer-exception-on-navigation-header-initialized-variables
navHeader=(RelativeLayout) LayoutInflater.from(this).inflate(R.layout.drawer_header, null);
navigationView.addHeaderView(navHeader); //This seems to add a SECOND "X" image
nameTV = (TextView) navHeader.findViewById(R.id.employeeFname);
lnameTV = (TextView) navHeader.findViewById(R.id.employeeLname);
closeDrawer = (ImageView) navHeader.findViewById(R.id.closedrawer);
profilePhoto = (ImageView) navHeader.findViewById(R.id.profilephoto);
businessesTV = (TextView) findViewById(R.id.businesses);
closeDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
drawerLayout.closeDrawer(Gravity.LEFT);
}
});
///////////////////////////////////////////////////////////////////////////
//INFORMATION FOR MENU/////////////////////
//PROFILE PHOTO
//currentUser = FirebaseAuth.getInstance().getCurrentUser();
//currentUserString = currentUser.getUid().toString();
setupDrawerLayout();
database = FirebaseDatabase.getInstance();
employeesRefPhoto = database.getReference("Employees").child(currentUserString).child("photoDownloadUrl");
employeesRefPhoto.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("onDataChange","Inside");
try {
photoUrl = dataSnapshot.getValue().toString();
Log.i("photoUrl", photoUrl);
Glide.with(getApplicationContext()).load(photoUrl).into(profilePhoto);
profilePhoto.setScaleType(ImageView.ScaleType.CENTER_CROP);
}
catch (NullPointerException e) {
Log.i("Null", e.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("Cancelled",databaseError.toString());
}
});
//////////////////////////////////////////////
//GET NAME//////////////////////////////////
//FIRST NAME
employeesRefFname = database.getReference("Employees").child(currentUserString).child("firstName");
employeesRefFname.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
Log.i("firstname", dataSnapshot.getValue().toString());
nameTV.setText(dataSnapshot.getValue().toString());
}
catch (Exception e) { Log.i("FNull?", e.toString()); }
}
#Override
public void onCancelled(DatabaseError databaseError) { Log.d("Cancelled",databaseError.toString()); }
});
//LAST NAME
employeesRefLname = database.getReference("Employees").child(currentUserString).child("lastName");
employeesRefLname.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
Log.i("lastname", dataSnapshot.getValue().toString());
lnameTV.setText(dataSnapshot.getValue().toString());
}
catch (Exception e) { Log.i("LNull?", e.toString()); }
}
#Override
public void onCancelled(DatabaseError databaseError) { Log.d("Cancelled",databaseError.toString()); }
});
//footerOnClick();
footerOnClick();
} //END OF ONCREATE
/////////////////////////////////////////////////////////////////////////////////
//INITIALIZE VIEWS
private void initViews(){
navHeader=(RelativeLayout) LayoutInflater.from(this).inflate(R.layout.drawer_header, null);
nameTV = (TextView) navHeader.findViewById(R.id.employeeFname);
lnameTV = (TextView) navHeader.findViewById(R.id.employeeLname);
menu = (ImageView) findViewById(R.id.menu);
closeDrawer = (ImageView) navHeader.findViewById(R.id.closedrawer);
profilePhoto = (ImageView) navHeader.findViewById(R.id.profilephoto);
businessesTV = (TextView) findViewById(R.id.businesses);
}
//INTENTS FOR THE FOOTER OF THE SCREEN
private void footerOnClick() {
businessesTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
startActivity(new Intent(HomeActivity.this, BusinessesActivity.class));
}
});
//EMPLOYEES
//PAYROLL REPORT
}
//MENU / DRAWER
//https://antonioleiva.com/navigation-view/
private void setupDrawerLayout() {
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override public boolean onNavigationItemSelected(MenuItem menuItem) {
//If Clicked...then get item and go to associated page
switch(menuItem.getTitle().toString())
{
case "Profile":
Log.i("Profile", menuItem.getTitle().toString());
startActivity(new Intent(HomeActivity.this, ProfileActivity.class));
/*case "Share":
startActivity(new Intent(HomeActivity.this, ProfileActivity.class));
case "Settings":
startActivity(new Intent(HomeActivity.this, ProfileActivity.class)); */
case "Logout":
Log.i("Logout", menuItem.getTitle().toString());
FirebaseAuth.getInstance().signOut();
//startActivity(new Intent(HomeActivity.this, LoginActivity.class));
}
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
}
//??????????????????????????????????????
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
} //END OF CLASS
Inside setupDrawerLayout() under onNavigationItemSelected() you have a switch statement.
In each case of the switch statement use break else all the following switch conditions may execute. Since the last case is to logout, the user might be getting signed out each time the switch statement executes.

How to add back button animation to Hamburger button animation

I am using appcompat v7 and support design 23.1.1.
I want to add back button in the hamburger button animation, when back pressed application will go back to started page.
Now in my application I have hamburger button. When it is pressed in main window (marked with orange rectangle) material navigation opens, selected Home (marked as red rectangle) when the application navigates to selected window there are hamburger (yellow rectangle) button again, and I would like to change it.
My MainActivity.java:
public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private static String TAG = MainActivity.class.getSimpleName();
private Toolbar mToolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new PagerAdapter(this));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getSupportFragmentManager().popBackStack();
}
});
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.action_search:
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
mToolbar.setTitle(title);
}
}
}
FragmentDrawer.java:
public class FragmentDrawer extends Fragment {
private static String TAG = FragmentDrawer.class.getSimpleName();
private RecyclerView recyclerView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavigationDrawerAdapter adapter;
private View containerView;
private static String[] titles = null;
private FragmentDrawerListener drawerListener;
public FragmentDrawer() {
}
public void setDrawerListener(FragmentDrawerListener listener) {
this.drawerListener = listener;
}
public static List<NavDrawerItem> getData() {
List<NavDrawerItem> data = new ArrayList<>();
// preparing navigation drawer items
for (int i = 0; i < titles.length; i++) {
NavDrawerItem navItem = new NavDrawerItem();
navItem.setTitle(titles[i]);
data.add(navItem);
}
return data;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// drawer labels
titles = getActivity().getResources().getStringArray(R.array.nav_drawer_labels);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new NavigationDrawerAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
drawerListener.onDrawerItemSelected(view, position);
mDrawerLayout.closeDrawer(containerView);
}
#Override
public void onLongClick(View view, int position) {
}
}));
return layout;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
toolbar.setAlpha(1 - slideOffset / 2);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static interface ClickListener {
public void onClick(View view, int position);
public void onLongClick(View view, int position);
}
static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public interface FragmentDrawerListener {
public void onDrawerItemSelected(View view, int position);
}
}
NavDrawerItem.java:
public class NavDrawerItem {
private boolean showNotify;
private String title;
public NavDrawerItem() {
}
public NavDrawerItem(boolean showNotify, String title) {
this.showNotify = showNotify;
this.title = title;
}
public boolean isShowNotify() {
return showNotify;
}
public void setShowNotify(boolean showNotify) {
this.showNotify = showNotify;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
DrawerActivity.java :
public class DrawerActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener{
private Toolbar mToolbar;
private FragmentDrawer drawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
drawerFragment = (FragmentDrawer)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
drawerFragment.setDrawerListener(this);
// display the first navigation drawer view on app launch
displayView(0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return true;
case R.id.action_search:
Toast.makeText(getApplicationContext(), "Search action is selected!", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDrawerItemSelected(View view, int position) {
displayView(position);
}
private void displayView(int position) {
Fragment fragment = null;
String title = getString(R.string.app_name);
switch (position) {
case 0:
fragment = new HomeFragment();
title = getString(R.string.title_home);
break;
case 1:
fragment = new FriendsFragment();
title = getString(R.string.title_friends);
break;
case 2:
fragment = new MessagesFragment();
title = getString(R.string.title_messages);
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.commit();
// set the toolbar title
getSupportActionBar().setTitle(title);
}
}
}
Try this way in your xml
<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:fitsSystemWindows="true">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_gravity="start"
android:background="#android:color/transparent"
android:minHeight="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/toolBarStyle"
app:titleTextAppearance="#style/Toolbar.TitleText" />
<android.support.v4.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:layout_below="#+id/toolbar"
android:fitsSystemWindows="true">
<RelativeLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="0dp"
android:background="#android:color/transparent" />
<fragment
android:id="#+id/navigation_drawer"
class="com.buzzintown.consumer.drawer.NavigationDrawerFragment"
android:layout_width="310dp"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/drawer_layout" />
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
If the activity figured in your third picture is a new one, you can just add the follow code in the new activity`s onCreate() method. it may help...
final ActionBar toolbar = getSupportActionBar();
if (toolbar != null) {
toolbar.setDisplayHomeAsUpEnabled(true);
}
If it`s in one same activity, and just different fragments through viewpager, use the Toolbar.setNavigationIcon() to change your up icon.

Custom SwitchPreference not saving value

When I access the PreferenceScreen, I notice that my custom switch is off. Then I turn it on and restart the app. I went back to the PreferenceScreen and the switch went back off. This doesn't happen when I use the default SwitchPreference. I am able to customize the SwitchPreference the way I want it to be, so the only problem is the switch value not saving. I have four files related to a customize SwitchPreference and all of the Preferences are placed in an extension of a PreferenceFragment
SettingsFragment.java
public class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Settings"
>
<com.example.CustomSwitchPreference
android:key="vibration"
android:title="vibration"
android:summary=""
android:defaultValue="true" />
</PreferenceScreen>
CustomSwitchPreference.java:
public class CustomSwitchPreference extends SwitchPreference {
public CustomSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomSwitchPreference(Context context) {
super(context);
}
#Override
protected View onCreateView( ViewGroup parent )
{
LayoutInflater li = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
return li.inflate( R.layout.customswitch_preference, parent, false);
}
/*
#Override
protected void onBindView(View view) {
MainActivity mainActivity = (MainActivity)getContext();
RelativeLayout relativeLayout = (RelativeLayout)mainActivity.findViewById(R.id.switch_frame);
Switch s = (Switch)relativeLayout.getChildAt(1);
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
persistBoolean(isChecked);
}
});
super.onBindView(view);
}
*/
}
customswitch_preference.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switch_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/switch_title"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:layout_alignParentStart="true"/>
<Switch
android:id="#+id/switch_pref"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
/>
</RelativeLayout>
MainActivity.java:
public class MainActivity extends Activity {
private ActionBar actionBar;
private boolean mInit = false;
private boolean showIcon = true;
private Menu m;
private GridFragment gridFragment;
private SettingsFragment settingsFragment;
public ImageButton startButton;
public TextView gameTimer;
public TextView mineCount;
public boolean isVibrating;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsFragment = new SettingsFragment();
actionBar = getActionBar();
actionBar.setTitle("Settings");
actionBar.setCustomView(R.layout.actionbar);
//actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
//actionBar.setBackgroundDrawable(new ColorDrawable(Color.BLACK));
ViewGroup actionBarViews = (ViewGroup)actionBar.getCustomView();
startButton = (ImageButton)(actionBarViews.findViewById(R.id.actionBarLogo));
mineCount = (TextView)actionBarViews.findViewById(R.id.topTextViewLeft);
gameTimer = (TextView)actionBarViews.findViewById(R.id.topTextViewRight);
startButton.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
startButton.setImageResource(R.drawable.smiley2);
break;
case MotionEvent.ACTION_UP:
restartGame();
break;
}
return false;
}
});
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/digital-7 (mono).ttf");
TextView textView;
int[] resources =
{R.id.textViewLeft,R.id.topTextViewLeft,R.id.textViewRight,R.id.topTextViewRight};
for(int r: resources) {
textView = (TextView) findViewById(r);
textView.setTypeface(myTypeface);
}
if (findViewById(R.id.fragment_container) != null){
if (savedInstanceState != null) {
return;
}
}
}
public void restartGame() {
startButton.setImageResource(R.drawable.smiley);
getFragmentManager().beginTransaction().remove(gridFragment).commit();
setText(999, gameTimer);
startGame();
}
private void startGame(){
gridFragment = new GridFragment();
gridFragment.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(R.id.fragment_container, gridFragment,"gridFragment").commit();
}
public void setText(int value, TextView textView){
value = Math.min(999,value);
value = Math.max(-99,value);
textView.setText(String.format("%03d",value));
}
#Override
protected void onStart() {
if (!mInit) {
mInit = true;
Database db = new Database(this);
db.deleteAllSessions();
db.close();
startGame();
}
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
m = menu;
return true;
}
private void openSettings(){
showIcon = false;
gridFragment.pauseTimer();
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(false);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.hide(gridFragment);
ft.add(android.R.id.content, settingsFragment).commit();
//ft.replace(android.R.id.content,settingsFragment);
}
private void updateSettings(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Map<String, ?> map = sharedPrefs.getAll();
for (Map.Entry<String, ?> entry : map.entrySet()) {
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
}
isVibrating = (Boolean)map.get("vibration");
}
private void closeSettings(){
showIcon = true;
onPrepareOptionsMenu(m);
actionBar.setDisplayShowCustomEnabled(true);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.show(gridFragment);
ft.remove(settingsFragment).commit();
//ft.replace(android.R.id.content,gridFragment);
gridFragment.resumeTimer();
}
#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) {
openSettings();
return true;
}
else if(id == R.id.backButton){
updateSettings();
closeSettings();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item= menu.findItem(R.id.action_settings);
item.setVisible(showIcon);
item = menu.findItem(R.id.backButton);
item.setVisible(!showIcon);
return super.onPrepareOptionsMenu(menu);
}
}
You're never actually setting or saving the state of the switch. You need to override onBindView to set the initial state of the view, and attach a checked change listener to the Switch (R.id.switch_pref) to listen for changes and persist them into SharedPreferences (you can call persistBoolean to do that).

Categories

Resources