NavigationView click listener not working - android

I am trying to handle NavigationView click listener for back button but it is not working.
navigationView.setOnClickListener may be enough but may be it's due to some other reason that's why added full class
MainActivity.class
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ActionBarDrawerToggle toggle;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
}
});
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, new CameraFragment()).commit();
}
#Override
public void onBackPressed() {
//super.onBackPressed();
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == android.R.id.home)
{
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}else if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new CameraFragment();
} else if (id == R.id.nav_gallery) {
fragment = new GalleryFragment();
} else if (id == R.id.nav_slideshow) {
fragment = new SlideShowFragment();
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if(fragment!=null){
if(item.isChecked())
{
if(getSupportFragmentManager().getBackStackEntryCount()==0){
drawer.closeDrawers();
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}else{
removeAllFragments();
getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.content_fragment, fragment).commit();
drawer.closeDrawer(GravityCompat.START);
}
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void removeAllFragments(){
getSupportFragmentManager().popBackStackImmediate(null,
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
public void replaceFragment(final Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.replace(R.id.content_fragment, fragment).addToBackStack("")
.commit();
}
public void updateDrawerIcon() {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
try {
Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
toggle.setDrawerIndicatorEnabled(false);
else
toggle.setDrawerIndicatorEnabled(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}, 50);
}
public void resetActionBar()
{
//display home
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
Answer found by Mike M Comment:
remove navigation.setOnClickListener and replace it to
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
}
});

Related

How to implement setDrawerLockMode or disable navigation drawer

I have a navigation drawer activity with fragments within it by using a fragment container. I have three fragments within it and I need one of it named locate_login to not contain my navigation drawer.
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); //nav drawer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
locate_login fragment = new locate_login();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void onSelectFragment(View v){ //ignore this
Fragment newFragment;
if(v == findViewById(R.id.trigger)){
newFragment = new locate_after();
}
else{
newFragment = new locate_before();
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is my locate_login fragment
public class locate_login extends Fragment{
public locate_login () {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.locate_login, container, false);
// Inflate the layout for this fragment
return rootView;
}
}
I will highly appreciate it if the answer will be detailed since I'm a beginner on Android Studio.
Create a class for some constant parameter. Declare some constant variable like:
Let say StringConstant.java :
public static final int LOCK_DRAWER = 1;
public static final int SHOW_DRAWER = 2;
When navigating from the drawer, use an Intent object as:
If you want to show the drawer, use:
intent.putExtra("SHOW_DRAWER", StringConstant.SHOW_DRAWER);
OR
If you do not want to show the drawer, use:
intent.putExtra("SHOW_DRAWER", StringConstant.LOCK_DRAWER);
Retrieve intent from your fragment class, you say locate_login.
int status = getActivity.getIntent().getIntExtra("SHOW_DRAWER", 0);
Check status:
if (status == String.Constant.LOCK_DRAWER){
lockDrawer();
}
public void lockDrawer() {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
To unlock the drawer:
public void unlockDrawer() {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}

Navigation Drawer open close pane not working with smoothness

This is my gif of problem. I am using navigation drawer, and I have done some code as per below but the pane close and open is not working with require smoothness.
This is my code:
public class SettingFlyout extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
SharedPreferences pref;
SharedPreferences.Editor editor;
public DrawerLayout drawer;
public ActionBarDrawerToggle toggle;
public NavigationView navigationView;
LinearLayout viewPager;
int roleId;
FragmentStack fragmentStack = FragmentStack.getInstance();
#Override
public void onPanelClosed(int featureId, Menu menu) {
super.onPanelClosed(featureId, menu);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting_flyout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView credits, num_credits, ttlscore, num_ttlscore, tutorNow;
final Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/GothamBookRegular.ttf");
View v = getLayoutInflater().inflate(R.layout.student_actionbar_view, null);
credits = (TextView) v.findViewById(R.id.credits);
credits.setTypeface(typeface);
viewPager = (LinearLayout) findViewById(R.id.viewpager);
Intent i = getIntent();
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int status = i.getIntExtra("status", 1);
String username = i.getStringExtra("username");
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
View view = navigationView.getHeaderView(0);
TextView TVuserName = (TextView) view.findViewById(R.id.personTextsettingflyout);
TVuserName.setText(username);
if (status == 0) {
roleId = Integer.parseInt(i.getStringExtra("roleId"));
}
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
Tablayout_with_viewpager withViewpager = new Tablayout_with_viewpager(status, roleId);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.viewpager, withViewpager);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
FragmentManager fragmentManager = getSupportFragmentManager();
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else
if (fragmentStack.size()==0) {
super.onBackPressed();
finish();
moveTaskToBack(true);
} else if (fragmentStack.size()>0) {
if (fragmentStack.size()<2 || fragmentStack.size()==2 || fragmentStack.isEmpty()){
super.onBackPressed();
finish();
moveTaskToBack(true);
SplashScreen splashScreen=new SplashScreen();
splashScreen.onBackPressed();
} else {
Fragment fragment = fragmentStack.pop();
if (fragment.getClass().equals(""))
Toast.makeText(getApplicationContext(), fragment.getClass().toString(), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), String.valueOf(fragmentStack.size()), Toast.LENGTH_SHORT).show();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.viewpager, fragment).commit();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment;
if (id == R.id.profile) {
Tablayout_with_viewpager tablayout_with_viewpager = new Tablayout_with_viewpager();
fragmentTransaction.replace(R.id.viewpager, tablayout_with_viewpager).commit();
// Handle the camera action
} else if (id == R.id.desired_tutor) {
DesiredTutor desiredTutor = new DesiredTutor();
fragmentTransaction.replace(R.id.viewpager, desiredTutor).commit();
} else if (id == R.id.payment_options) {
BuyCredits buyCredits=new BuyCredits();
fragmentTransaction.replace(R.id.viewpager, buyCredits).commit();
} else if (id == R.id.lesson_tracking) {
lessonTracking lessonTracking=new lessonTracking();
fragmentTransaction.replace(R.id.viewpager, lessonTracking).commit();
} else if (id == R.id.TTL_Score) {
TTL_Score ttl_score = new TTL_Score();
fragmentTransaction.replace(R.id.viewpager, ttl_score).commit();
} else if (id == R.id.History) {
History history = new History();
fragmentTransaction.replace(R.id.viewpager, history).commit();
} else if (id == R.id.notification) {
Notification notification = new Notification();
fragmentTransaction.replace(R.id.viewpager, notification).commit();
} else if (id == R.id.support) {
Support support = new Support();
fragmentTransaction.replace(R.id.viewpager, support).commit();
} else if (id == R.id.sign_out) {
pref=getSharedPreferences("loginStatus", Context.MODE_PRIVATE);
editor=pref.edit();
editor.clear();
editor.apply();
Intent i = new Intent(getApplicationContext(), Login.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
else if (id== R.id.daily_game){
TutorGuides dailyGame= new TutorGuides();
fragmentTransaction.replace(R.id.viewpager, dailyGame).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
what should I do to make it smoother?
Every time used this code it not need to use this code every time define in once a time:-
fragmentTransaction.replace(R.id.viewpager, desiredTutor).commit();
Create a method:-
public static void showFragment(Fragment fragment, String Tag) {
FragmentManager manager = activity.getSupportFragmentManager();
FragmentTransaction transcation = manager.beginTransaction();
transcation.replace(R.id.viewpager, fragment, Tag);
transcation.addToBackStack(Tag);
transcation.commit();
}
and use this :-
switch (item.getItemId())
{
case R.id.desired_tutor:
showFragment(new DesiredTutor(), "");
break;
case R.id.payment_options:
showFragment(new BuyCredits(), "");
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
You are initiating it everytime. Its wrong. Just initialize it once and use that object to open and close the drawer. remove that code from item selected listener and put it in to Oncreate to initialize it once.
Use below code to make it perfect :
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
toggle.syncState();
}
ActionBarDrawerToggle toggle;
toggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(toggle);

Android fragments stack - back (up) button does not work

I'm completely new at Android. I was quite surprised that Android Studio does not have a template for navigation between fragments. I have spent several days now, but still cannot make my code work properly.
I have single activity and two fragments - MainFragment and AboutFragment. About is accessible via drawer menu item. I want to return to MainFragment by pressing back action bar button. The problem is button is not working. Can anyone help me?
Complete minimal Android Studio project:
test.zip
Here is my activity class:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener,
MainFragment.OnFragmentInteractionListener, AboutFragment.OnFragmentInteractionListener {
private DrawerLayout drawer;
private boolean zOrderSet = false;
private ActionBarDrawerToggle toggleListener;
private FragmentManager.OnBackStackChangedListener mOnBackStackChangedListener =
new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
syncActionBarArrowState();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toggleListener = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
if (!zOrderSet) {
drawer.bringChildToFront(drawerView);
drawer.requestLayout();
drawer.invalidate();
zOrderSet = true;
}
}
public void onDrawerClosed(View view) {
syncActionBarArrowState();
}
public void onDrawerOpened(View drawerView) {
toggleListener.setDrawerIndicatorEnabled(true);
}
};
drawer.setDrawerListener(toggleListener);
toggleListener.syncState();
getSupportFragmentManager().addOnBackStackChangedListener(mOnBackStackChangedListener);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().beginTransaction().replace(R.id.flContent, MainFragment.newInstance("", "")).commit();
}
#Override
protected void onDestroy() {
getSupportFragmentManager().removeOnBackStackChangedListener(mOnBackStackChangedListener);
super.onDestroy();
}
private void syncActionBarArrowState() {
boolean empty = getSupportFragmentManager().getBackStackEntryCount() == 0;
toggleListener.setDrawerIndicatorEnabled(empty);
getSupportActionBar().setDisplayHomeAsUpEnabled(!empty);
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (toggleListener.isDrawerIndicatorEnabled() && toggleListener.onOptionsItemSelected(item)) {
return true;
}
int id = item.getItemId();
if (id == android.R.id.home && getSupportFragmentManager().popBackStackImmediate()) {
return true;
}
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentTransaction ta = getSupportFragmentManager().beginTransaction();
try {
switch (item.getItemId()) {
case R.id.nav_restart:
ta.replace(R.id.flContent, MainFragment.class.newInstance());
break;
case R.id.nav_about:
ta.replace(R.id.flContent, AboutFragment.class.newInstance()).addToBackStack(null);
break;
default:
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ta.commit();
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
#Override
public void onBackPressed(){
getActivity().getFragmentManager().beginTransaction().remove(this).commit();
}

Material design: naviagtion drawer with tabs and recyclerview

I have a problem with the navigation drawer. I want to know how to display recyclerview when the user clicks on different element of each menu.
Here are some source code and an illustrative capture
N.B: different menu items ("Accueil, Contacts Staff, etc ...") are in an .xml file in the layout.
MainActiviy.java
public class MainActivity extends AppCompatActivity {
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
setupWindowAnimations();
//définir la toolbr en tant qu'actionbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, 0, 0);
drawerLayout.setDrawerListener(drawerToggle);
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
return true;
}
});
//on remplit notre viewpager, comme à notre habitude
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(int position) {
return RecyclerViewFragment.newInstance();
}
#Override
public CharSequence getPageTitle(int position) {
return "Tab " + position;
}
#Override
public int getCount() {
return 1;
}
});
//indique au tablayout quel est le viewpager à écouter
tabLayout.setupWithViewPager(viewPager);
}
private void setupWindowAnimations() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Explode explode = new Explode();
getWindow().setExitTransition(explode);
Fade fade = new Fade();
getWindow().setReenterTransition(fade);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
#OnClick(R.id.fab)
public void onFabClick() {
Snackbar.make(fab, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Undo", new View.OnClickListener() {
#Override
public void onClick(View v) {
}
}).show();
}
}
Sample source code for you
public class NavActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Hope this helps you
Not understand exactly what you want. Where do you want to display recycler view? You already have OnNavigationItemSelectedListener, just check which menu you have clicked and do what you want:
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
 case R.id.contact:
// do anything you want, ex
showContactList();
break;
}
the function to show your contact list
private void showContactList(){
List<Contact> data = getYourDataSomeHow();
yourAdapter.setData(data);
yourRecyclerView.setAdapter(yourAdapter);
}

Switching and clicking on fragments inside navigation drawer

I have made navigation drawer in Android Studio.
Right now each fragment from drawer is leading to nowhere.
I need to know how can I switch between fragments and click on each one
I know i need to make new fragment, but what method to use so I can click on Settings from navigation drawer so it lead me to fragment Share?
Here is my code;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
You are in the right direction. Just add the Fragment class in each of the Navigation items like below
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment = null;
FragmentManager fragmentManager = getSupportFragmentManager();
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new DefaultFragment();
fragmentManager.beginTransaction().replace(R.id.first_container, fragment).commit();
} else if (id == R.id.nav_gallery) {
fragment = new ItemListFragment();
fragmentManager.beginTransaction().replace(R.id.first_container, fragment).commit();
}
}
at the end of onCreate(Bundle savedInstanceState)method, you can set the default Fragment to open on Activity load.
FragmentManager fragmentManager = getSupportFragmentManager();
DefaultFragment fragment = new DefaultFragment();
fragmentManager.beginTransaction().replace(R.id.first_container, fragment).commit();
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.`enter code here`
int id = item.getItemId();
FragmentManager fragmentManager =getSupportFragmentManager();
GoogleMap googleMap =getSupportFragmentManager();
if (id == R.id.alarme){
} else if (id == R.id.map) {
fragmentManager.beginTransaction().replace(R.id.contenedor,new mapposta()).commit();
} else if (id == R.id.parametre) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;

Categories

Resources