I have one activity and some fragments and try to use navigation controller. I choose menu item, fragment changed. But when I press back button only drawer opens.
Here is my code:
public class MainActivity extends AppCompatActivity implements HomeFragment.OnFragmentInteractionListener,
LibraryFragment.OnFragmentInteractionListener, UserProfileFragment.OnFragmentInteractionListener {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private Toolbar toolbar;
public NavController navController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
drawerLayout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
initDrawer();
View header = navigationView.getHeaderView(0);
View userPicture = header.findViewById(R.id.user_pic);
userPicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showUserProfile();
}
});
}
#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(#NonNull MenuItem item) {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
switch (item.getItemId()){
case android.R.id.home:
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (navController.popBackStack()){
} else {
drawer.openDrawer(GravityCompat.START);
}
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
private void initDrawer(){
Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
ActionBar actionBar = getSupportActionBar();
NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout);
NavigationUI.setupWithNavController(navigationView, navController);
}
private void showUserProfile(){
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
navController.navigate(R.id.userProfileFragment);
}
}
What do I do wrong?
Thanks in advance
Related
I want the button like in this picture https://i.stack.imgur.com/XPbkL.jpg
]public class NavigationDrawer extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
private Toolbar toolbar;
private NavigationView navigationView;
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
textView=findViewById(R.id.text_view);
toolbar=findViewById(R.id.tool);
toolbar.setTitle("");
setSupportActionBar(toolbar);
drawerLayout=findViewById(R.id.drawer_layout);
navigationView=findViewById(R.id.drawer);
navigationView.setNavigationItemSelectedListener(this);
toggle=new ActionBarDrawerToggle(this,drawerLayout,toolbar,
open,R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
String itemName= (String) menuItem.getTitle();
textView.setText(itemName);
closeDrawer();
return true;
}
public void closeDrawer()
{
drawerLayout.closeDrawer(GravityCompat.START);
}
public void openDrawer()
{
drawerLayout.openDrawer(GravityCompat.START);
}
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.START))
{
closeDrawer();
}
super.onBackPressed();
}
}
This is my code please tell me how to increase the size of navigation drawer button which is humburger button. I tried different solutions but it did not worked
You can override the default size of icon navigation drawer like this ( in dimens.xml )
<dimen name="design_navigation_icon_size" tools:override="true">XXdp</dimen>
Replace XX with your own value in dp
I have created an app which uses one activity (Navigation Drawer) and a fragment. But I'm unable to use toolbar back button to navigate back from the fragment to the main activity. Hardware back button works perfectly. I know that I need to override onOptionsItemSelected, catch android.R.id.home, check if there is something in the back stack and then pop it. After changing the fragment, "burger" button changes to "back arrow", but when I click on it the overridden method "onOptionsItemSelected" is never called, rather on click of the back button NavigationDrawer menu opens.
NOTE: I have referred many answers in the StackOverflow including THIS which is the same as that of my problem but that did not work for me. I have been working on this for a week any help is greatly appreciated. Please do not down vote. 1
Here is my code
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void init() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
Log.d("Backstack Count", String.valueOf(getSupportFragmentManager().getBackStackEntryCount()));
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
showUpButton(false);
} else {
showUpButton(true);
}
}
});
}
private void showUpButton(boolean show) {
// To keep states of ActionBar and ActionBarDrawerToggle synchronized,
// when you enable on one, you disable on the other.
// And as you may notice, the order for this operation is disabled first, then enable - VERY VERY IMPORTANT.
if (show) {
// Remove hamburger
mDrawerToggle.setDrawerIndicatorEnabled(false);
// Show back button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// when DrawerToggle is disabled i.e. setDrawerIndicatorEnabled(false), navigation icon
// clicks are disabled i.e. the UP button will not work.
// We need to add a listener, as in below, so DrawerToggle will forward
// click events to this listener.
} else {
// Show hamburger
mDrawerToggle.setDrawerIndicatorEnabled(true);
invalidateOptionsMenu();
}
// So, one may think "Hmm why not simplify to:
// .....
// getSupportActionBar().setDisplayHomeAsUpEnabled(enable);
// mDrawer.setDrawerIndicatorEnabled(!enable);
// ......
// To re-iterate, the order in which you enable and disable views IS important #dontSimplify.
}
#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) {
// super.onCreateOptionsMenu(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) {
switch (item.getItemId()) {
case android.R.id.home:
// onBackPressed();
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
return true;
}
// return false;
// return super.onOptionsItemSelected(item);
return true;
}
#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
displayImportFrag();
} 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;
}
public void displayImportFrag() {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Log.d("called", "new frag");
ImportFragment importFragment = new ImportFragment();
ft.add(R.id.fragment_frame, importFragment).addToBackStack(null).commit();
}
}
ImportFragment.java
public class ImportFragment extends Fragment {
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.import_fragment, container, false);
return rootView;
}
}
ERROR:
DrawerToggle may not show up because NavigationIcon is not visible.
You may need to call actionbar.setDisplayHomeAsUpEnabled(true);
public class Homepage extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
int storeid;
String storename;
private RecyclerView recyclerView;
ProductAdapter adapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<ProductClass> Products = new ArrayList<>();
Database database;
public DrawerLayout mDrawerLayout;
public ActionBarDrawerToggle mDrawerToggle;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
database = new Database();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawerLayout,toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
assert mDrawerLayout != null;
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(Homepage.this);
load();
View hView = navigationView.getHeaderView(0);
TextView nav_name = (TextView)hView.findViewById(R.id.textView);
nav_name.setText(storename);
Products = database.getstoreproducts(storeid);
if (Products == null)
Toast.makeText(Homepage.this, "Store is empty", Toast.LENGTH_LONG).show();
else {
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new ProductAdapter(Products, Homepage.this);
recyclerView.setAdapter(adapter);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater m = getMenuInflater();
return true;
}
public void load() {
SharedPreferences sharedPreferences = getSharedPreferences("MyStore", Context.MODE_PRIVATE);
storename = sharedPreferences.getString("storename", "Default");
storeid = sharedPreferences.getInt("storeid", -1);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
// Handle the camera action
} else if (id == R.id.nav_add) {
Intent intent = new Intent(Homepage.this, addnewproduct.class);
startActivity(intent);
}
else if (id == R.id.nav_user) {
Intent intent = new Intent(Homepage.this, storeinfo.class);
startActivity(intent);
}
else if (id == R.id.nav_logout) {
SharedPreferences sharedPreferences = getSharedPreferences("MyStore", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("logged", "unsuccessful");
editor.commit();
Intent intent = new Intent(Homepage.this, MainActivity.class);
startActivity(intent);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
T tried everything i found but couldn't find any solution. please help.
You need to add the below lines for custom Navigation Icon,
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.logo);
add the following lines after initializing actionbar in OnCreate()
actionbar.setDisplayHomeAsUpEnabled(true);
If it doesn't work, try this:
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_HOME_AS_UP);
I got a problem that DrawerLayout does not close smoothly and it stops in the middle for a while, it totally closes after finish replacing fragment. In coding I close DrawerLayout before replacing fragment (productList class). In productList class, it calls asynctask to get all the product list from server meanwhile running progress bar. Ideally when user clicks menu, DrawerLayout will close at once and productList fragment will be loading all the product list. It seems to me DrawerLayout close event waits for productList's asynctask. Any suggestion greatly appreciated.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {
public String tag = "MainActivity";
Context mContext;
//User Object
User user;
//Control
TextView txtName, txtPosition, txtLogout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
user = Constants.getUser();
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
//NavigationView Header
View headerView = navigationView.getHeaderView(0);
txtName = (TextView) headerView.findViewById(R.id.nav_header_main_name) ;
txtName.setText(user.getName().toString());
txtLogout = (TextView) headerView.findViewById(R.id.nav_header_main_logout);
txtLogout.setOnClickListener(this);
navigationView.setNavigationItemSelectedListener(this);
//Add Menu in navigationView
Menu myMenu = navigationView.getMenu();
myMenu.clear();
myMenu.add(0,Integer.parseInt("01"),0,"Product List");
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//close drawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
// replace fragment
int id = item.getItemId();
FragmentManager fragmentManager = getSupportFragmentManager();
if(Constants.DEBUG) {
Toast.makeText(mContext, " Menu Id " + String.valueOf(id), Toast.LENGTH_LONG).show();
}
fragmentManager.beginTransaction()
.replace(R.id.container,new productList())
.commit();
return true;
}
#Override
public void onClick(View v) {
//Log out onclick
if(v.getId() == R.id.nav_header_main_logout){
this.finish();
}
}
}
This probably happens beacuse the Navigation Drawer's animation and the creation of the Fragment happens at the same time.
You can solve it by starting your Fragment with a small delay-
handler.postDelayed(new Runnable() {
#Override
public void run() {
// replace fragment
int id = item.getItemId();
FragmentManager fragmentManager = getSupportFragmentManager();
if(Constants.DEBUG) {
Toast.makeText(mContext, " Menu Id " + String.valueOf(id), Toast.LENGTH_LONG).show();
}
fragmentManager.beginTransaction()
.replace(R.id.container,new productList())
.commit();
}
}, 300);
How do you close the NavigationDrawer after clicking to open a new Fragment. I have tried a few things but just can't get it to work
MainActivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, BookAFragment.newInstance())
.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);
}
#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) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_strains) {
Toast.makeText(getApplicationContext(),"Book A Selected", Toast.LENGTH_SHORT).show();
BookAFragment fragment = new BookAFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container,fragment);
fragmentTransaction.commit();
return true;
} else if (id == R.id.nav_recipes) {
Toast.makeText(getApplicationContext(),"Book B Selected", Toast.LENGTH_SHORT).show();
BookBFragment fragment = new BookBFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container,fragment);
fragmentTransaction.commit();
return true;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}