The navigation drawer code is as follows:
private void ShowNavigationDrawer() {
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Populate the Navigtion Drawer with options
mDrawerList = (ListView) findViewById(R.id.left_drawer);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer_white, R.string.drawer_open,
R.string.drawer_close);
// Drawer Item click listeners
mDrawerList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selectItemFromDrawer(position);
}
});
}
The other used methods are:
/*
* Called when a particular item from the navigation drawer is selected.
*/
private void selectItemFromDrawer(int position) {
selectItem(position);
getSupportActionBar().setTitle(mNavItems.get(position).mTitle);
// Close the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
To select the correct fragment to load within one activity:
/** Swaps fragments in the main content view */
private void selectItem(int position) {
switch (position) {
case 1:
currentFragment = new ABCFragment();
break;
case 2:
currentFragment = new SearchTabFragment();
break;
default:
currentFragment = new HomeFragment();
break;
}
currentFragment.setArguments(getIntent().getExtras());
fragmentManager = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.main_content_frame, currentFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
// Highlight the selected item, update the title, and close the drawer
mDrawerList.setItemChecked(position, true);
}
To select(highlight) the particular item from the navigation drawer programatically within another fragment I'm calling the following method but it is NOT working!
// Highlight the selected item
homeActivity.mDrawerList.setItemChecked(position, true);
Where is the problem? Can anyone help me to fix this issue?
You can try to implement the navigation drawer with the new NavigationView instead of the ListView. Something like this:
<android.support.design.widget.NavigationView
android:id="#+id/nv_navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:itemIconTint="#color/navigation_item_selector"
app:itemTextColor="#color/navigation_item_selector"
app:itemBackground="#android:drawable/screen_background_light_transparent"
android:layout_gravity="start" />
You can populate the NavigationView with a menu .xml file. Then you can easily select programmatically an item like this:
mNavigationView.setCheckedItem(R.id.my_item_1);
and the drawable selector will handle the work of the highlighting in the correct manner. For example, this is my selector (navigation_item_selector.xml):
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/red" android:state_checked="true" />
<item android:color="#color/red" android:state_pressed="true" />
<item android:color="#color/black" />
</selector>
PS I know its not the solution that you want, but its the solution that you might find helpful.
Since highlighting means giving it a background color as you want. If you do not want it in the click event of items but want it otherwise, you have to give it manually on your navigation drawer adapter. like this
public void onBindViewHolder(MyViewHolder holder, int position) {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
if(position==0)
{
holder.llnavdrawer.setBackgroundResource(R.color.black);
}
else if(position==2)
{
holder.llnavdrawer.setBackgroundResource(R.color.grey);
}
else if(position==4)
{
holder.llnavdrawer.setBackgroundResource(R.color.green);
}
else if(position==6)
{
holder.llnavdrawer.setBackgroundResource(R.color.black);
}
}
you can ask if the thing you wanted is not this.
Good luck!!
Related
This is the beahviour of my App (only 1 is right, of course):
Of course I want only one item at the moment checked.
I divided the items in two groups (to add the divider, see my previous question: How add horizontal separator in navdrawer? )
This is the nav_menu.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single"
android:id="#+id/group1" >
<item
android:id="#+id/home"
android:checked="false"
android:icon="#drawable/ic_home_black_24dp"
android:title="#string/list_home" />
<item
android:id="#+id/list_event"
android:checked="false"
android:icon="#drawable/ic_list_black_24dp"
android:title="#string/list_event" />
</group>
<group
android:checkableBehavior="single"
android:id="#+id/group2" >
<item
android:id="#+id/settings"
android:checked="false"
android:icon="#drawable/ic_settings_black_24dp"
android:title="#string/settings" />
</group>
</menu>
This is the BaseApp that manage the NavDrawer:
package com.xx.views;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.view.View;
import com.xx.R;
import com.xx.mappers.DateManager;
public class BaseApp extends AppCompatActivity {
//Defining Variables
protected String LOGTAG = "LOGDEBUG";
protected Toolbar toolbar;
protected NavigationView navigationView;
protected DrawerLayout drawerLayout;
private DateManager db = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.base_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, new DashboardFragment());
fragmentTransaction.commit();
setNavDrawer();
// make home as checked
navigationView.getMenu().getItem(0).setChecked(true);
}
private void setNavDrawer(){
// Initializing Toolbar and setting it as the actionbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Initializing NavigationView
//Setting Navigation View Item Selected Listener to handle the item click of the navigation menu
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
case R.id.home:
DashboardFragment dashboardFragment = new DashboardFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, dashboardFragment,"DASHBOARD_FRAGMENT");
fragmentTransaction.commit();
return true;
case R.id.list_event:
ListEventFragment fragmentListEvent = new ListEventFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragmentListEvent);
fragmentTransaction.commit();
return true;
case R.id.settings:
SettingsFragment fragmentSettings = new SettingsFragment();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame, fragmentSettings);
fragmentTransaction.commit();
return true;
default:
return true;
}
}
});
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
ActionBarDrawerToggle actionBarDrawerToggle =
new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.open_drawer, R.string.close_drawer){
#Override
public void onDrawerClosed(View drawerView) {
// Code here will be triggered once the drawer closes as we dont want anything
// to happen so we leave this blank
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
// Code here will be triggered once the drawer open as we dont want anything
// to happen so we leave this blank
super.onDrawerOpened(drawerView);
}
};
//Setting the actionbarToggle to drawer layout
drawerLayout.setDrawerListener(actionBarDrawerToggle);
//calling sync state is necessay or else your hamburger icon wont show up
actionBarDrawerToggle.syncState();
}
private void eraseTable(){
db=new DateManager(this);
db.resetTable();
}
#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) {
// 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);
}
}
Thank you very much
This could help you: Try to removing the tag android:checkableBehavior="single" from xml and set android:checkable = “true” for each item individually, then declare a MenuItem object in the activity and in onNavigationItemSelected event if previously declared MenuItem object is not null then set checked value as false for it and then save current selected menuItem received as parameter to earlier declared MenuItem object.
This will set checked selection on even subitems.
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
}
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
prevMenuItem = menuItem;
return true;
I found this solutions here
If you are using groups and android:checkableBehavior="single", then all you need to do is set the single item as the checked item in the navigation view (not simply the item as checked with item.setChecked(true)):
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
//item.setChecked(true); //Won't work, will leave previous item checked too.
navigationView.setCheckedItem(id); //this will check single item
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
Now, whether you select or emulate select for an item, it will check only one item at a time.
Put both group inside single group an set
android:checkableBehavior="single"
Create a parent group
You would have to implement a custom adapter, custom/model, custom function to uncheck other items on click.
I suggest you to use this library. Its a material navigation drawer implementation, it already has all this logic implemented. If you dont want to go with a lib, them you should check how its done on this library code and adapt to your needs.
as the title suggests, I'm trying to implement all of these features at once. Originally I had a fully functioning side-nav with a SwipeRefreshLayout which holds a list view (using a custom list adapter). I then added a ViewPager inside of the SwipeRefreshLayout, and everything mostly works…except that as I swipe the list view does not appear in the new 'tabs' sometimes. Most of the time I see the first page and list view, I swipe right, nothing, I swipe right, nothing, I swipe left, list view, I swipe to the beginning, nothing.
I should add that everything is entirely dynamic, the navigation items are received from my server (which is also the number of pages) and each page has a custom list adapter with different list items. All of this dynamic information seems to be received and adapted correctly per page swipe etc.
Now for the code!
Drawer layout with swiperefreshlayout and view pager embedded. "drawer.xml"
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<!-- android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
The drawer is given a fixed width in dp and extends the full height of
the container. A solid background is used for contrast
with the content view. -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/grey_lighter"
android:dividerHeight="1dp"
android:background="#FFFFFF"/>
</android.support.v4.widget.DrawerLayout>
Listview which holds the custom list items created dynamically in the activity "dashboard.xml":
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/LV_dashboard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1" >
</ListView>
Now for the fragment activity :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this.getApplicationContext();
navItems = new ArrayList<String>();
this.setContentView(R.layout.drawer);
mMerchantIds = Session.get().getMerchID(); //array retrieved from cache used for api
mCustomerPagerAdapter = new CustomerPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mCustomerPagerAdapter);
mTitle = mDrawerTitle = getTitle();
mNavTitles = getResources().getStringArray(R.array.nav_array); //I realize this isn't dynamic, I haven't gotten around to that just yet.
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
connection = new WiselyRequest();
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.nav_item, mNavTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
This branches off into two parts, we'll start with the Drawer:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments (this is not what the pager does)
Fragment fragment = null;
fragment = new CustomerFragment();
Bundle args = new Bundle();
args.putString(KEY_MERCHANT_ID, (mMerchantIds.get(position)));
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mNavTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
Here is the view pager:
public class CustomerPagerAdapter extends FragmentPagerAdapter {
public CustomerPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
Fragment fragment = new CustomerFragment();
Bundle args = new Bundle();
Log.d("Wisely", "merchants: "+mMerchantIds.get(i));
args.putString(KEY_MERCHANT_ID, (mMerchantIds.get(i))); // Our object is just an integer :-P
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// For this contrived example, we have a 100-object collection.
return mMerchantIds.size(); //equal to the number of merchantss (that many customer objects)
}
#Override
public CharSequence getPageTitle(int position) {
return "OBJECT " + (position + 1);
}
}
Here is the customer fragment that both the drawer and pager are utilizing and where on refresh is handled:
public class CustomerFragment extends Fragment implements OnRefreshListener {
private View rootView;
SwipeRefreshLayout swipeLayout;
public CustomerFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
String merchantID = args.getString(KEY_MERCHANT_ID);
if(connection.checkConnectivity(getApplicationContext())){
getRecentCustomers(API.getRecentCustomers()+"?merchant_id="+merchantID); //api call works totally fine, and correctly sets up the adapter
}
else
Toast.makeText(DashboardActivity.this, "Need to be connected to the internet!", 4000).show();
rootView = inflater.inflate(R.layout.dashboard, container, false);//inflates the dashboard
swipeLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light);
registerClickCallback(rootView);
return rootView;
}
#Override
public void onRefresh() {
if(connection.checkConnectivity(getApplicationContext()))
reloadActivity(); //literally turns the activity on and off without animation
else
Toast.makeText(DashboardActivity.this, "Need to be connected to the internet!", 4000).show();
}
I believe the issue exits in my layouts, not in the list adapter or customer fragment which seem to be working fine (every time I swipe to a new page the api is called and the correct data is put into the list view. I just can't see it. Also I realize that the navdrawer is not dynamic, but my bigger issue at the moment is being able to swipe through multiple list views on pages. When I change my customerFragment to inflate a simple text view with a number in it, it seems to work fine, except that the first page never goes away, other pages just pile on top of it (I think this has to do with the framelayout in the drawer but removing it breaks the code because my nag drawer relies on it). Any suggestions?
I think, you will have to create your own classes extending DrawerLayout or ViewPager.
Inside of your classes you have to Override methods:
onInterceptTouchEvent() - here you evaluate TouchEvent and return true, if you are intercepting it (not passing to the child View)
You have to tweak the conditions of intercepting based on what you are trying to achieve.
Guide is here:
http://developer.android.com/training/gestures/viewgroup.html
I downloaded the sample app for the Navigation Drawer from
http://developer.android.com/training/implementing-navigation/nav-drawer.html
Now I'd like to add an icon to a specific item in the list; for example
Logout_icon + "Logout"
How can I do this? (Code please)
Assuming you are implementing the Navigation Drawer by a ListView, you will need to modify the layout for the list item by adding an ImageView. Then you should modify the adapter you use to populate the ListView so that it sets the src of the ImageView accordingly.
Quoting the guide you linked:
// Set the adapter for the list view
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
That's where most of your changes will be wired: specifying a layout containing a TextView and and ImageView and creating a new Adapter.
As a convenience, you might create a class called something like NavDrawerItem which will have two fields: one for the icon, the other the caption which you'll display through a TextView.
In your adapter, be sure to consider the menu items for which you won't be displaying an icon.
try this
private ActionBarDrawerToggle mDrawerToggle;
mDrawerToggle=new ActionBarDrawerToggle(this,
mdrawerlayout,
R.drawable.ic_whats_hot,
R.string.app_name,
R.string.app_name)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View view)
{
getActionBar().setTitle(R.string.app_name);
invalidateOptionsMenu();
}
};
public boolean onOptionsItemSelected(MenuItem item)
{
if(mDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
switch(item.getItemId())
{
case R.id.action_settings:
intent1=new Intent(MainActivity.this,ActivitySetting.class);
startActivity(intent1);
return true;
case R.id.action_websearch:
intent1=new Intent(Intent.ACTION_VIEW,Uri.parse("http://http://www.vogella.com/"));
startActivity(intent1);
return true;
default :
return super.onOptionsItemSelected(item);
}
}
try this in coding and in XML file
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_websearch"
android:showAsAction="always"
android:icon="#drawable/action_search"
android:title="search"/>
<item
android:id="#+id/action_settings"
android:title="Settings"
android:icon="#drawable/ic_launcher"
>
</item>
<item
android:id="#+id/action_logout"
android:title="logout"
android:icon="#drawable/ic_launcher"
/>
I have created a simple navigation drawer using this tutorial , the items in the nav drawer link to their respective fragments, but once i click on an item in the nav drawer i want it to take me to ie a list view. As far i see its that it only links to a java class that extends Fragment, as soon as i mention extend ListFragment it freaks out.
This is the NavigationDrawer I use:
First of all I set a Click listener to the ListView inside the NavigationDrawer
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
DrawerItemClickListener its a custom class
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
This calls to selectItem(int position)
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (position) {
case 0:
ft.replace(R.id.content_frame, new FirstFragment());
setTitle("First");
break;
case 1:
ft.replace(R.id.content_frame, new SecondFragment());
setTitle("Second");
break;
case 2:
ft.replace(R.id.content_frame, new ThirdFragment());
setTitle("Third");
break;
}
ft.commit();
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mRelativeLayout);
}
Here you can set any Fragment of any kind you want. With this you won't have any Fragment type mismatch.
Also you can follow an official NavigationDrawer example provided by Android developers.
http://developer.android.com/training/implementing-navigation/nav-drawer.html
Hope it helps.
The navigation drawer in my app is not closing. I am using activities instead of fragments. When i click on any item in the listview, it opens other activities as it should but when i go back, the drawer is still open. I have tried using DrawerLayout.closeDrawers(); but it did not work. How do I close the navigation drawer?
Here is my code:
Java
public class MainActivity extends FragmentActivity {
final String[] data ={"Aluminium","Gold","Zinc"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.left_drawer);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
switch (pos){
case 0:
Intent i = new Intent(MainActivity.this,Aluminium.class);
startActivity(i);
break;
case 1:
Intent i2 = new Intent(MainActivity.this,Gold.class);
startActivity(i2);
break;
case 2:
Intent i3 = new Intent(MainActivity.this,Zinc.class);
startActivity(i3);
break;
}
}
});
}
}
XML
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:background="#000000"
android:layout_height="match_parent" >
</FrameLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="220dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="1dp"
android:background="#000000"/>
</android.support.v4.widget.DrawerLayout>
have you tried :
mDrawerLayout.closeDrawer(drawerListView);
You can add this before calling startActivity()
In continuation to others answers and # Chinmay Dabke question of 'but the drawer closes half then pauses and then closes fully' in one of the comments, here is what you could do:
first as others suggested,
this line is missing. drawer.closeDrawer(navList);
And as far as the pausing of drawer is concerned while closing, you could do something like this.
use a Runnable and a Handler like this:
mRunnable = = new Runnable() {
#Override
public void run() {
//say
selectItem(pos); //Implement your switch case logic in this func
}
}
and then in the onDrawerClosed overrided method
#Override
public void onDrawerClosed(View view) {
if (mRunnable != null) {
mHandler.post(mRunnable);
mRunnable = null;
}
}
Hope this helps!
I would suggest you to use fragments for navigation drawer and to solve this issue of drawer not closing properly, I found this article very useful (using fragments). http://www.michenux.net/android-asynctask-in-fragment-best-pratices-725.html
Call
drawer.closeDrawer(navList);
in onItemClick() method
Try
drawer.closeDrawer(Gravity.START);
Your drawer gravity is start so Use that to close the corresponding drawer
I didn't see any code where you are closing the ListView from drawer... close the ListView Drawer on ListItem click...
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.closeDrawer(navList);
switch (pos){
case 0:
Intent i = new Intent(MainActivity.this,Aluminium.class);
startActivity(i);
break;
case 1:
Intent i2 = new Intent(MainActivity.this,Gold.class);
startActivity(i2);
break;
case 2:
Intent i3 = new Intent(MainActivity.this,Zinc.class);
startActivity(i3);
break;
}
}
});
You need to close the drawer on list item click
drawer.closeDrawer(navList);
Also what is the use of FrameLayout in your xml. It is not used as a container to add or replace fragments
call the drawer.closeDrawer(navList); function before switch case
use
if(drawer.isDrawerOpen(navList))
{
drawer.closeDrawer(navList);
}
In onResume() and start of onItemClick() method.
or you can try another approach..run a Ui thread when you are selecting drawer item
private void selectDrawerItemItem(final int position){
//Toast.makeText(getApplicationContext(), "ItemClicked", Toast.LENGTH_SHORT).show();
darwer.closeDrawer(navList);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Fragment fragment = new Fragment(Activity.this);
Bundle args = new Bundle();
args.putInt(Fragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).commit();
// update selected item and title, then close the drawer
navList.setItemChecked(position, true);
setTitle(" " + navListTitles[position]);
}
}, 200);
// update the main content by replacing fragments
}
I was having the same problem.
I used
mDrawerLayout.closeDrawer(drawerListView);
before starting my new activity. It beautifully slides the drawer back in.
private DrawerLayout mDrawerLayout;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.closeDrawers();
it works
Here is the code:
Lets say you have the drawer class
in your activity call the class as and make a vaiable and assign it(put the drawer layout within a fragment for smoother user experience)
Drawer drawer;
drawer = (Drawer)getActivity().getSupportFragmentManager().findFragmentById(R.id.theid);
drawer.mDrawerLayout.closeDrawer(Gravity.END);
//End for right and Start for left
Hope it helps