I have implemented navigation drawer in my project.Everything is fine and the project is all set.I only have a problem with my drawer.On click of every item i have sub items but i do not want to show it in expandable list view,I want to open another sub drawer containing sub items right next to my main navigation drawer. How should i proceed.Please Help.
Code in Context
MainActivity
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
private String[] mTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initToolbar();
mTitles=getResources().getStringArray(R.array.drawer_titles);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList=(ListView)findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
private void initToolbar() {
toolbar=(Toolbar)findViewById(R.id.toolbar);
toolbar.setTitle(R.string.toolbar_title);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_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
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:id="#+id/toolbar"
android:background="#efeaea"
android:layout_height="50dp"/>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_below="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<LinearLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
<!-- 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:dividerHeight="2dp"
android:background="#ffffff"/>
</android.support.v4.widget.DrawerLayout>
</RelativeLayout>
you can implement custom Expandable adapter
list_item.xml //child view inside group
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="55dip"
android:orientation="vertical"
android:divider="#color/black">
<TextView
android:id="#+id/lblListItem"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="#dimen/textSize14"
android:typeface="sans"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:layout_marginLeft="80dp"/>
</LinearLayout>
list_group.xml //parent view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="100dp"
android:orientation="horizontal"
android:padding="3dp"
android:dividerPadding="10dp">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/navImage"
android:layout_margin="#dimen/padding_10dp"
android:layout_gravity="center"/>
<TextView
android:id="#+id/lblListHeader"
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="left|center"
android:layout_weight=".5"
android:textSize="#dimen/textSize20"/>
<TextView
android:layout_width="50dp"
android:layout_height="match_parent"
android:id="#+id/Collapser"
android:textSize="#dimen/textSize20"
android:textAllCaps="true"
android:text="+"
android:layout_gravity="center_vertical"
android:gravity="center"
android:layout_weight=".5"
android:textStyle="normal"/>
</LinearLayout>
ExpandableListAdapter
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private int[] headerIcons;
public ExpandableListAdapter(Context context,int[] headerIcons, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this.headerIcons = headerIcons;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_item, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.lblListItem);
txtListChild.setText(childText);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
ImageView headerImage = (ImageView)convertView.findViewById(R.id.navImage);
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setText(headerTitle);
TextView lvlPlusMinus=(TextView)convertView.findViewById(R.id.Collapser);
if(getChildrenCount(groupPosition)!=0)
{
lvlPlusMinus.setTypeface(null, Typeface.NORMAL);
lvlPlusMinus.setText("+");
if(isExpanded)
{
lvlPlusMinus.setTypeface(null, Typeface.NORMAL);
lvlPlusMinus.setText("-");
}
}
else
{
lvlPlusMinus.setText("");
}
headerImage.setImageResource(headerIcons[groupPosition]);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
In your Navigation drawer
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
// private ListView mDrawerListView;
private View mFragmentContainerView;
ExpandableListAdapter listAdapter;
ExpandableListView mDrawerListView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
private int lastExpandedPosition = -1;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
Map<String, String> params;
HashMap<String, String> userDetails;
public Fragment fragment = null;
String tag,URL ;
android.support.v4.app.FragmentManager fragmentManager;
FragmentTransaction transaction;
Handler handler;
Runnable runnable;
private final Handler mDrawerHandler = new Handler();
/**
* AppointmentRequest ♠♠
*/
ProgressDialog bar ;
public static final NavigationDrawerFragment NavUtils = new NavigationDrawerFragment();
public static NavigationDrawerFragment getInstance() {
return NavUtils;
}
public NavigationDrawerFragment() {
}
View contentView;
SessionManager session;
TextView doctorName;
ImageView docImage;
int[] headerIcons;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentManager = getFragmentManager();
transaction = fragmentManager.beginTransaction();
session = new SessionManager(getActivity());
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
headerIcons = new int[]{
R.drawable.home,
R.drawable.profile,
R.drawable.logout
};
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
contentView = inflater.inflate(
R.layout.fragment_navigation_drawer_with_topheader, container, false);
mDrawerListView = (ExpandableListView) contentView.findViewById(R.id.expList);
doctorName = (TextView)contentView.findViewById(R.id.docName);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
selectItem(position);
}
});
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(getActivity(), headerIcons, listDataHeader, listDataChild);
mDrawerListView.setAdapter(listAdapter);
mDrawerListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
mDrawerListView.smoothScrollToPosition(groupPosition);
mDrawerListView.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
mDrawerListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v, final int groupPosition, long id) {
final String selected = (String) listDataHeader.get(groupPosition);
mDrawerListView.smoothScrollToPosition(groupPosition);
mDrawerHandler.removeCallbacksAndMessages(null);
mDrawerHandler.postDelayed(new Runnable() {
#Override
public void run() {
//Toast.makeText(getActivity(), selected, Toast.LENGTH_SHORT).show();
}
}, 250);
if (groupPosition == 0 ||)//close drawer if no child
mDrawerLayout.closeDrawers();
return false;
}
});
/**
* Expandable list child on click listener
*/
mDrawerListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, final int groupPosition, final int childPosition, long id) {
final String selected = (String) listAdapter.getChild(
groupPosition, childPosition);
mDrawerListView.smoothScrollToPosition(groupPosition);
mDrawerHandler.removeCallbacksAndMessages(null);
mDrawerHandler.postDelayed(new Runnable() {
#Override
public void run() {
// Toast.makeText(getActivity(), selected, Toast.LENGTH_SHORT).show();
}
}, 250);
mDrawerLayout.closeDrawers();
return true;
}
});
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return contentView;
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding Child in Parent
listDataHeader.add("Home");//0
listDataHeader.add("Profile");//1
listDataHeader.add("Sign out");//2
List<String> Profile = new ArrayList<String>();
Casefile.add("Child 1");
Casefile.add("Child 2");
listDataChild.put(listDataHeader.get(0), new ArrayList<String>());// Header, Child data
listDataChild.put(listDataHeader.get(1), Profile);
listDataChild.put(listDataHeader.get(2), new ArrayList<String>());//if no child
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the 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
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.dehaze);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.dehaze, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
)
{
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE");
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
/*if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}*/
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
/**
* Diplaying view for selected nav drawer list item
* */
private void displayView(final int position) {
// update the content by replacing fragments
switch (position) {
case 0:
mDrawerLayout.closeDrawers();
tag = "HomeFragment";
fragment = new HomeFragment();
break;
case 1:
mDrawerLayout.closeDrawers();
tag = "ProfileFragment";
fragment = new ProfileFragment();
break;
case 2:
mDrawerLayout.closeDrawers();
tag = "Signout";
fragment= null;
//Signout
break;
default:
break;
}
if (fragment != null) {
// update selected item and title, then close the drawer
mDrawerListView.setItemChecked(position, true);
mDrawerListView.setSelection(position);
mDrawerListView.smoothScrollToPosition(position);
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.container, fragment, tag);
transaction.commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
Related
I am currently working on app which will have a notification drawer with 2 sections -
A dashboard of status requests (pending, submitted, in process, completed). I have named it DashboardFragment.java
A notification center which shows all messages received from the 3rd party Java server(via Google Cloud Messaging server). I have named it PushMessagesFragment.java
The problem that I am facing is that when I receive notifications from the server, the "unread messages" count is not reset to zero once I open the PushMessages Fragment.
Also, the unread message count is ONLY updated when I click on the notification; whereas it should update (and show me the count of number of unread messages) even if I simply open the navigation drawer.
Here is a screenshot -
http://i.imgur.com/hSM9Fxm.png "Unread Message Count Not Updated"
For the Navigation Drawer, I am using a Model Class named NavDrawerItem.java which has the following code -
public class NavDrawerItem {
private String title;
private int icon;
private String count = "0";
// boolean to set visiblity of the counter
private boolean isCounterVisible = false;
public NavDrawerItem(String title, int icon) {
this.title = title;
this.icon = icon;
}
public NavDrawerItem(String title, int icon, boolean isCounterVisible, String count) {
this.title = title;
this.icon = icon;
this.isCounterVisible = isCounterVisible;
this.count = count;
}
public String getTitle() {
return this.title;
}
public int getIcon() {
return this.icon;
}
public String getCount() {
return this.count;
}
public boolean getCounterVisibility() {
return this.isCounterVisible;
}
public void setTitle(String title) {
this.title = title;
}
public void setIcon(int icon) {
this.icon = icon;
}
public void setCount(String count) {
this.count = count;
}
public void setCounterVisibility(boolean isCounterVisible) {
this.isCounterVisible = isCounterVisible;
}
}
I am using a Custom Adapter named NavigationDrawerListAdapter for my Navigation Drawer.
public class NavigationDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList < NavDrawerItem > navDrawerItems;
public NavigationDrawerListAdapter(Context context, ArrayList < NavDrawerItem > navDrawerItems) {
this.context = context;
this.navDrawerItems = navDrawerItems;
}#
Override
public int getCount() {
return navDrawerItems.size();
}#
Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}#
Override
public long getItemId(int position) {
return position;
}#
Override
public View getView(int position, View convertView, ViewGroup parent) {
NavDrawerViewHolder viewHolder;
if (convertView == null) {
viewHolder = new NavDrawerViewHolder();
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.nav_drawer_list_item, null);
viewHolder.imgIcon = (ImageView) convertView.findViewById(R.id.icon);
viewHolder.txtTitle = (TextView) convertView.findViewById(R.id.title);
viewHolder.txtCount = (TextView) convertView.findViewById(R.id.counter);
convertView.setTag(viewHolder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
viewHolder = (NavDrawerViewHolder) convertView.getTag();
}
viewHolder.imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
viewHolder.txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if (navDrawerItems.get(position).getCounterVisibility()) {
viewHolder.txtCount.setText(navDrawerItems.get(position).getCount());
} else {
// hide the counter view
viewHolder.txtCount.setVisibility(View.GONE);
}
return convertView;
}
static class NavDrawerViewHolder {
ImageView imgIcon;
TextView txtTitle;
TextView txtCount;
}
}
Here is the code for the fragment NavigationDrawerFragment which inflates the custom list layout and attaches the custom adapter to the ListView for Navigation Drawer.
public class NavigationDrawerFragment extends Fragment {
UserSessionManager session;
ShareBlankRegIDWithServer appUtilBlank ;
AsyncTask shareNARegidTask;
String regId;
Button notifCount;
static int mNotifCount = 0;
public int NOTIFICATION_ID;
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
//import Model class and Adapter Class for Navigation Drawer Items
private ArrayList<NavDrawerItem> navDrawerItems;
private NavigationDrawerListAdapter adapter;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//get value of current Notification_ID
NOTIFICATION_ID = NotificationID.getID();
// Create an Instance of User Session Manager
session = new UserSessionManager(getActivity().getApplicationContext());
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Dashboard (with a counter)
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Notification Center (with a counter)
//this is where I am setting the Notification ID to the list item with the counter i.e. Notification Center
navDrawerItems.add(new NavDrawerItem(
navMenuTitles[1],
navMenuIcons.getResourceId(1, -1),
true,
String.valueOf(NOTIFICATION_ID)));
// Download Reports (without a counter)
// navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Recycle the typed array
navMenuIcons.recycle();
// setting the nav drawer list adapter
adapter = new NavigationDrawerListAdapter(getActivity().getApplicationContext(),
navDrawerItems);
//set adapter
mDrawerListView.setAdapter(adapter);
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// 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
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.e("Drawer", "Closed");
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Log.e("Drawer","Opened");
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
Log.d("Drawer Open", "Menu global Inflated");
showGlobalContextActionBar();
adapter.notifyDataSetChanged();
Log.e("NavDrawerFragment", "notifyDataSetChanged");
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_logout) {
//ask if user really wants to sign out
// if yes then ->
// Clear the User session data
// and redirect user to LoginActivity
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
// set title
alertDialogBuilder.setTitle("Quit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really wish to logout ?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
appUtilBlank = new ShareBlankRegIDWithServer();
shareNARegidTask = new MyAsyncClass().execute(null, null, null);
//Toast.makeText(getActivity().getApplicationContext(), "Signing Out", Toast.LENGTH_SHORT).show();
//finish MainActivity to NOT make the users go back to Dashboard upon pressing BACK button
Intent launchNextActivity;
launchNextActivity = new Intent(getActivity(), LoginActivity.class);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(launchNextActivity);
//clear User Detail SharedPrefs
session.logoutUser();
Log.d("CLEARED", "Preferences");
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
public class MyAsyncClass extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
Log.d("NavigationDrawerFragment doInBackround", "share Blank RegId with Server");
//get RegID from SharedPrefs
//regId = new RegisterInBackground(getActivity().getApplicationContext()).getRegistrationId(getActivity().getApplicationContext());
String result = appUtilBlank.shareBlankRegIdWithAppServer(getActivity().getApplicationContext(), regId);
return result;
}
#Override
protected void onPostExecute(String result) {
//Toast.makeText(getApplicationContext(), result,Toast.LENGTH_LONG).show();
}
}
}
Finally, I've managed to get the result I wanted.
First, I changed the setText() value in NavigationDrawerListAdapter.
if (navDrawerItems.get(position).getCounterVisibility()) {
//viewHolder.txtCount.setText(navDrawerItems.get(position).getCount());
//The next line is where I made the change
viewHolder.txtCount.setText(String.valueOf(NotificationID.getID()));
Log.e("Counter Value set to", String.valueOf(NotificationID.getID()));
}
Then, in my Singleton class NotificationID, I changed the setZero() method body from
public static int setToZero()
{
return 0;
}
to
public static int setToZero()
{
c = 0;
return c;
}
The final change I made was in PushMessagesFragment.java since I wanted to reset the counter to zero whenever I opened that fragment.
//set notification id to zero
NOTIFICATION_ID = NotificationID.setToZero();
//NOTIFICATION_ID = NotificationID.setID();
Log.e("Push Messages NOTIFICATION_ID", String.valueOf(NotificationID.getID()));
Now my app seems to be working fine, showing actual notification count when I receive messages, and showing ZERO count when I open PushMessage Fragment.
I created this header and i want to add it at the top of my listview in my navigation drawer the problem is that i don't know where to add it
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="178dp"
android:background="#android:color/holo_red_dark"
android:orientation="vertical"
android:weightSum="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="56dp"
android:orientation="vertical"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
>
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:textColor="#ffffff"
android:text="Antoine Dupond"
android:textSize="14sp"
android:textStyle="bold"
/>
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_marginLeft="16dp"
android:layout_marginTop="5dp"
android:text="dupond#gmail.com"
android:textSize="14sp"
android:textStyle="normal"
/>
</LinearLayout>
<de.hdodenhof.circleimageview.CircleImageView
android:layout_width="70dp"
android:layout_height="70dp"
android:src="#drawable/ic_launcher"
android:layout_marginLeft="16dp"
android:layout_marginTop="38dp"
android:id="#+id/circleView"
/>
</RelativeLayout>
My fragment with custom adapter :
public class NavigationDrawerFragment extends Fragment {
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
private NavigationDrawerCallbacks mCallbacks;
private ActionBarDrawerToggle mDrawerToggle;
private MyAdapter myAdapter;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
myAdapter=new MyAdapter(getActivity());
mDrawerListView.setAdapter(myAdapter);
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(),
mDrawerLayout,
R.string.app_name,
R.string.app_name
)
{
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
public class MyAdapter extends BaseAdapter {
private Context context;
String [] socialSites ;
int [] images ={R.drawable.cafe,R.drawable.com,R.drawable.share,R.drawable.set,R.drawable.help};
public MyAdapter(Context context){
this.context=context;
socialSites = context.getResources().getStringArray(R.array.social);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = null;
if (convertView==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.custom_row,parent,false);
}
else{
row=convertView;
}
TextView titletexview = (TextView) row.findViewById(R.id.textView);
ImageView titleimageview =(ImageView) row.findViewById(R.id.imageView2);
titletexview.setText(socialSites[position]);
titleimageview.setImageResource(images[position]);
return row;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public Object getItem(int position) {
return socialSites[position];
}
#Override
public int getCount() {
return socialSites.length;
}
}
}
My mainactivity :
public class Nav extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nav);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment obj= null;
ListFragment listfragment = null;
switch (position) {
case 0:
listfragment= new F1_fr();
break;
case 1:
obj= new F6_fr();
break;
case 2:
obj= new F3_fr();
break;
case 3:
obj= new F4_fr();
break;
case 4:
obj= new F5_fr();
break;
}
if (obj != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, obj)
.commit();
}
else if (listfragment != null) {
// do stuff if its a listfragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, listfragment)
.commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
case 5:
mTitle = getString(R.string.title_section5);
break;
case 6:
mTitle = getString(R.string.title_section6);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.nav, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}*/
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_nav, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((Nav) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
and the layout :
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:choiceMode="singleChoice"
android:divider="#android:color/transparent" android:dividerHeight="0dp"
android:background="#ffe7e7e7"
tools:context="com.example.gweltaz.coffy3.NavigationDrawerFragment"
/>
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/drawer_layout"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context="com.example.gweltaz.coffy3.Nav">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout android:id="#+id/container" 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.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
the container. -->
<fragment android:id="#+id/navigation_drawer"
android:layout_width="#dimen/navigation_drawer_width" android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.example.gweltaz.coffy3.NavigationDrawerFragment"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
Inflate the layout and add it as a header to the ListView.
In onCreateView:
View header = inflater.inflate(R.layout.header, mDrawerListView, false);
mDrawerListView.addHeaderView(header, null);
Hi i just generate a navigation drawer using the sample in android studio and in my navagation drawer fragment (where the listview is) i have this code :
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
getString(R.string.title_section5),
getString(R.string.title_section6),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// 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
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
I want to add icon in front of each item of the list view but i dont know how to do this because i dont understand the whole code of the navigation drawer
Create a custom ArrayAdapter and use a custom layout inside it which has an ImageView and a TextView
Try this
The xml file(call it whatever you want):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textViewListItem"
android:layout_marginTop="25dp"
android:layout_marginLeft="10dp"
android:layout_gravity="center_horizontal" />
<ImageView
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="-40dp"
android:id="#+id/imageView"
android:src="#drawable/ic_launcher" />
</LinearLayout>
Create a class that will be your adapter, how your list wants to be(have an imageview, have 3 textviews, etc)
public class ListAdapter extends Activity {
private int imageId;
private String itemName;
public ListaAdapter(int imageId, String itemName) {
super();
this.imageId = imageId;
this.itemName = itemName;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}
then in your activity that you would like the drawer to be implemented try
//instanciate components
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerList;
private List<ListAdapter> drawerList = new ArrayList<ListAdapter>();
//in the onCreate method build 3 methods and organize your code
buildDrawer();
populateDrawerList();
buildListDrawer();
private void populateDrawerList() {
drawerList.add(new ListaAdapter(R.drawable.icon_1, "String 1"));
drawerList.add(new ListaAdapter(R.drawable.icon_2, "String 2"));
}
private void buildDrawer() {
mDrawerLayout = (DrawerLayout)findViewById(R.id.your_drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(YourActivity.this, mDrawerLayout, R.drawable.your_drawer_icon, "Open", "Closed"){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle("Drawer Opened");
invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActionBar().setTitle("Drawer Closed");
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void buildListDrawer() {
mDrawerList = (ListView)findViewById(R.id.listViewDrawer);
ArrayAdapter<ListAdapter> adapter = new MyDrawerArrayAdapter();
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MyActivity.this, "You have chosen " + drawerList.get(position).getItemName(), Toast.LENGTH_SHORT).show();
}
});
}
and then your modified Adapter that extends ArrayAdapter:
private class MyDrawerArrayAdapter extends ArrayAdapter<ListAdapter> {
public MyDrawerArrayAdapter() {
super(MyActivity.this, R.layout.drawer_list_item_layout, drawerList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View drawerView = convertView;
if(drawerView == null){
drawerView = getLayoutInflater().inflate(R.layout.drawer_list_item_layout, parent, false);
}
ListAdapter currentPosition = drawerList.get(position);
ImageView drawerImage = (ImageView)drawerView.findViewById(R.id.your_drawerImage);
drawerImage.setImageResource(currentPosition.getImageId());
TextView drawerText = (TextView)drawerView.findViewById(R.id.your_drawerText);
drawerText.setText(currentPosition.getItemName());
return drawerView;
}
}
Step 01 -
Have your res/drawable folder ready with appropriate icons.
Step 02 -
In your values/string.xml add below
<string-array name="mydrawerList">
<item>item 1</item>
<item>item 2</item>
<item>item 3</item>
</string-array>
<array name="mydrawerList_icons">
<item>#drawable/ic_for_item1</item>
<item>#drawable/ic_for_item2</item>
<item>#drawable/ic_for_item3</item>
</array>
make sure you have icons in the "mydrawerList_icons" ordered as "mydrawerList" order.
Step 03 -
in your NavigationDrawerFragment.java add below lines
private String[] listTitles;
private TypedArray listIcons;
in onCreate()
listTitles = getResources().getStringArray(R.array.mydrawerList);
listIcons = getResources().obtainTypedArray(R.array.mydrawerList_icons);
Step 04 -
instead of this
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
getString(R.string.title_section5),
getString(R.string.title_section6),
}));
type this
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
listTitles)
{
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
int resourceId = listIcons.getResourceId(position, 0);
Drawable drawable = getResources().getDrawable(resourceId);
((TextView) v).setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
return v;
}
});
Let me know the output.
I have implemented the Navigation Drawer into my new app. But I cannot get the App name from ActionBar to toggle the Navigation Drawer. However, when I drag the navigation drawer, the ActionBar respond to this action by changing to an arrow.
Here is my code:
services_activity_main.xml
<LinearLayout
android:orientation="vertical"
android:id="#+id/container_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/title_bar_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
<LinearLayout
android:id="#+id/contents_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp">
</LinearLayout>
<LinearLayout
android:id="#+id/navigation_bar_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
<FrameLayout
android:id="#+id/services_navigation_drawer_layout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start">
</FrameLayout>
</android.support.v4.widget.DrawerLayout>
services_fragment_navigation_drawer.xml
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/services_navigation_drawer_gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
android:choiceMode="multipleChoice"
android:focusable="true"
android:focusableInTouchMode="true"
android:background="#EEE" />
MainActivity.java
public class MainActivity
extends Activity
implements BaseControllerFragment.ControllerCallbacks,
ServicesNavigationDrawerFragment.NavigationDrawerCallbacks {
public final static String TAG = "MainActivity";
LinearLayout titleBarLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.services_activity_main);
titleBarLayout = (LinearLayout) findViewById(R.id.title_bar_layout);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.services_navigation_drawer_layout,
new ServicesNavigationDrawerFragment(),
TAG + "." + ServicesNavigationDrawerFragment.TAG).commit();
}
#Override
public void updateTitleBar(View view) {
titleBarLayout.removeAllViews();
titleBarLayout.addView(view);
titleBarLayout.invalidate();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
switch (position) {
case 0:
replaceContainerContents(new BuildLicenseControllerFragment());
return;
case 1:
replaceContainerContents(new BuildLicenseControllerFragment());
return;
}
}
private void replaceContainerContents(BaseControllerFragment controllerFragment) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.contents_layout,
controllerFragment,
TAG + "." + controllerFragment.TAG).commit();
}
}
ServicesNavigationDrawerFragment.java
public class ServicesNavigationDrawerFragment extends Fragment {
public final static String TAG = "ServicesNavigationDrawerFragment";
String[] titles = {
"String 1", // 0
"String 2" // 1
};
int[] images = {
R.drawable.service_build_license,
R.drawable.service_build_license
};
private final static String STATE_SELECTED_POSITION = "SELECTED_POSITION";
private final static String PREF_USER_LEARNED_DRAWER = "USER_LEARNED_DRAWER";
private int selectedPosition = 0;
private boolean fromSavedInstance;
private boolean userLearnedDrawer;
GridView drawerGridView;
DrawerLayout drawerLayout;
FrameLayout navigationDrawerLayout;
ActionBarDrawerToggle drawerToggle;
private NavigationDrawerCallbacks callbacks;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
userLearnedDrawer = sharedPreferences.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if(savedInstanceState != null) {
selectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
fromSavedInstance = true;
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
drawerGridView = (GridView) inflater.inflate(R.layout.services_fragment_navigation_drawer, container, false);
drawerGridView.setAdapter(new ServicesAdapter(titles, images));
drawerGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
return drawerGridView;
}
#Override
public void onAttach(final Activity activity) {
super.onAttach(activity);
try {
callbacks = (NavigationDrawerCallbacks) activity;
drawerLayout = (DrawerLayout) activity.findViewById(R.id.activity_services_drawer_layout);
navigationDrawerLayout = (FrameLayout) activity.findViewById(R.id.services_navigation_drawer_layout);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, R.string.app_name, R.string.app_name) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.i(TAG, "Drawer Closed!");
if (!isAdded()) {
return;
}
// activity.invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Log.i(TAG, "Drawer Opened!");
if (!isAdded()) {
return;
}
if( ! userLearnedDrawer) {
userLearnedDrawer = true;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
sharedPreferences.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
// activity.invalidateOptionsMenu();
}
};
if( ! userLearnedDrawer && ! fromSavedInstance) {
drawerLayout.openDrawer(navigationDrawerLayout);
}
drawerLayout.post(new Runnable() {
#Override
public void run() {
drawerToggle.syncState();
}
});
drawerLayout.setDrawerListener(drawerToggle);
} catch(ClassCastException e) {
throw new ClassCastException(activity.getClass() + " must implements NavigationDrawerCallbacks interface.");
}
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, selectedPosition);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(int position) {
selectedPosition = position;
if(drawerGridView != null) {
drawerGridView.setItemChecked(position, true);
}
if(drawerLayout != null) {
drawerLayout.closeDrawer(navigationDrawerLayout);
}
if(callbacks != null) {
callbacks.onNavigationDrawerItemSelected(position);
}
}
private class ServicesAdapter extends BaseAdapter {
public final static String TAG = "ServicesAdapter";
private Context context;
private LayoutInflater inflater;
private String[] titles;
private int[] images;
private ServicesAdapter(String[] titles, int[] images) {
if(titles.length != images.length) {
throw new RuntimeException("You Must Provide Same Number of Titles and Images.");
}
context = getActivity();
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.titles = titles;
this.images = images;
}
#Override
public int getCount() {
return images.length;
}
#Override
public Object getItem(int position) {
return titles[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = null;
if(convertView != null) {
textView = (TextView) convertView;
} else {
textView = (TextView) inflater.inflate(R.layout.services_layout_drawer_item, parent, false);
}
Log.i(TAG, textView.getCompoundDrawables()[1].getBounds().toString());
Drawable drawable = context.getResources().getDrawable(images[position]);
drawable.setBounds(new Rect(0, 0, 128, 128));
textView.setText(titles[position]);
textView.setCompoundDrawables(null, drawable, null, null);
return textView;
}
}
public interface NavigationDrawerCallbacks {
public void onNavigationDrawerItemSelected(int position);
}
}
You shouldn't handle your navigation drawer from fragment.
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, R.string.app_name, R.string.app_name) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
Log.i(TAG, "Drawer Closed!");
if (!isAdded()) {
return;
}
// activity.invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
Log.i(TAG, "Drawer Opened!");
if (!isAdded()) {
return;
}
if( ! userLearnedDrawer) {
userLearnedDrawer = true;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
sharedPreferences.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
// activity.invalidateOptionsMenu();
}
};
if( ! userLearnedDrawer && ! fromSavedInstance) {
drawerLayout.openDrawer(navigationDrawerLayout);
}
drawerLayout.post(new Runnable() {
#Override
public void run() {
drawerToggle.syncState();
}
});
drawerLayout.setDrawerListener(drawerToggle);
} catch(ClassCastException e) {
throw new ClassCastException(activity.getClass() + " must implements NavigationDrawerCallbacks interface.");
}
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, selectedPosition);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}a
Shift above code from fragment to your MAinActivity.java
Make sure you have everything on your drawerToggle like follows
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
I'm using this tutorial to add sliding menu to my app:
http://www.tutorialsbuzz.com/2014/03/android-sliding-menu-navigation-drawer.html
I went completely as said in the tutorial but it doesn't respond to the click events,
(I put log.d in the onClickListener and see that it even not go inside the on clickListener)
(it shows the list icon and title perfectly(i don't get any error, exception,..) but i could't debug why it doesn't invoke the onClickListener..)
Thanks for your help in advance
public class MainActivity extends ActionBarActivity {
/** slide menu **/
String[] menutitles;
TypedArray menuIcons;
/** nav drawer title **/
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*******
*
* for sliding menu
*
* **************/
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
i, -1));
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
// *******#for sliding menu*************
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.drawer_layout, new PlaceholderFragment())
.commit();
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Log.d("in list listener", Integer.toString(position));
updateDisplay(position);
}
}
#SuppressLint("NewApi")
private void updateDisplay(int position) {
android.app.Fragment fragment = null;
switch (position) {
case 0:
fragment = new FB_Fragment();
break;
case 1:
fragment = new GP_Fragment();
break;
case 2:
fragment = new TB_Fragment();
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#SuppressLint("NewApi")
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#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);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
and this is custom adapter:
public class CustomAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItem;
CustomAdapter(Context context, List<RowItem> rowItem) {
this.context = context;
this.rowItem = rowItem;
}
private class ViewHolder {
ImageView icon;
TextView title;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_tem, null);
holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
holder.title = (TextView) convertView.findViewById(R.id.title);
RowItem row_pos = rowItem.get(position);
// setting the image resource and title
holder.icon.setImageResource(row_pos.getIcon());
holder.title.setText(row_pos.getTitle());
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
#Override
public int getCount() {
return rowItem.size();
}
#Override
public Object getItem(int position) {
return rowItem.get(position);
}
#Override
public long getItemId(int position) {
return rowItem.indexOf(getItem(position));
}
and this is list_tem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#fff"
android:padding="5dp" >
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/icon"
android:gravity="center_vertical"
android:textColor="#color/bgc1"
android:textSize="18sp" />
<ImageView
android:id="#+id/icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:contentDescription="imgdesc" />
</RelativeLayout>
Find your navigation layout container and set this after config drawerToggle:
navigationContainer.bringToFront();
drawerLayout.requestLayout();
you need to create fragment for each listitems , still if your are not able to resolve then you can download the code from this Link : http://download.tutorialsbuzz.com/subscribers/index_slidemenu.php