How do I update unread notification counter in the Navigation Drawer? - android

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.

Related

Navigation Drawer Submenu

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

Android activity crashes when populating the listview with data from external databse in the form of JSON

here is the logcat error in image:
with error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.erp.navigationdrawer/com.erp.navigationdrawer.Notices}: java.lang.NullPointerException
This is my code of main activity which other activity extends to have a navigation drawer now on clicking notices in navigation drawer webservice is called and data comes but activity crashes and shows up:
ERROR AT mDrawerToggle.syncState();
Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer);
// if (savedInstanceState == null) {
// // on first time display view for first nav item
// // displayView(0);
// }
}
public void set(String[] navMenuTitles, TypedArray navMenuIcons) {
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items
if (navMenuIcons == null) {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i]));
}
} else {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i],
navMenuIcons.getResourceId(i, -1)));
}
}
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// getSupportActionBar().setIcon(R.drawable.ic_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, // nav menu toggle icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
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);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
switch (position) {
case 0:
Intent intent = new Intent(this, Courses.class);
startActivity(intent);
finish();// finishes the current activity
break;
case 1:
Intent intent2 = new Intent(this, Notices.class);
startActivity(intent2);
finish();
break;
case 2:
Intent intent3 = new Intent(this, Placements.class);
startActivity(intent3);
finish();
break;
default:
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* 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 toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
Below is the code for Notices activity that crashes up **AND ITS IS THE ONLY ACTIVITY AMONG NAVIGATION DRAWER TO CRASH:
private void loadservice(String url) {
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.get(url, null, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http response
// code '200'
#Override
public void onSuccess(String response) {
try {
JSONArray obj = new JSONArray(response);
for (int i = 0; i < obj.length(); i++) {
JSONObject jsonChild = obj.getJSONObject(i);
heading = jsonChild.optString("heading").toString();
content = jsonChild.optString("content").toString();
date = jsonChild.optString("date".toString());
System.out.println(heading + content + date);
entity = new NoticeEntity();
entity.setNotice_heading(heading);
entity.setNotice_content(content);
entity.setNotice_date(date);
arraylist.add(entity);
}
} catch (JSONException e) {
System.out.println(" Exception raised : " + e.getMessage());
e.printStackTrace();
}
}
});
ListView listView = (ListView) findViewById(R.id.notice_listview);
NoticeAdapter adapter = new NoticeAdapter(this, R.layout.custom_notice,
arraylist);
listView.setAdapter(adapter);
}
Here is my **NOTICE ADAPTER ** code below:
public class NoticeAdapter extends ArrayAdapter<NoticeEntity> {
private Context context;
public NoticeAdapter(Context context, int resourceId,
ArrayList<NoticeEntity> items) {
super(context, resourceId, items);
this.context = context;
}
/* private view holder class */
private class ViewHolder {
TextView heading;
TextView content;
TextView date;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
NoticeEntity entity = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_notice, null);
holder = new ViewHolder();
holder.heading = (TextView) convertView
.findViewById(R.id.txtvw_notice_heading);
holder.content = (TextView) convertView
.findViewById(R.id.txtvw_notice_content);
holder.date = (TextView) convertView
.findViewById(R.id.txtvw_notice_date);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.heading.setText(entity.getNotice_heading());
holder.content.setText(entity.getNotice_content());
holder.date.setText(entity.getNotice_date());
return convertView;
}
}
onPostCreate will be executed immediately after onCreate. You're accessing a member variable called mDrawerToggle in your onPostCreate, but it is not assigned before onPostCreate is called. It is normal convention to assign all your views to member variables during onCreate immedately after you call setContentView. In your case, it's being assigned in a method called "set" where I can't see that it's ever being called.
Try moving all the view-related code from set into onCreate.

Custom navigation drawer list view

Hi i'm new to the android world and i generated a navigation drawer with the default template in android studio.I'm looking for a way to make section in my listview like this :![enter image description here][1]
How i want my listview to be : https://camo.githubusercontent.com/7043b4240e1be50bb68b3f101c1f9815c9be0f11/68747470733a2f2f7261772e6769746875622e636f6d2f6e656f6b7265652f4d6174657269616c4e617669676174696f6e4472617765722f6d61737465722f73637265656e312e6a7067
Here is the code of my fragment,i really don't know how to do this and i want to have the image on the top with the email like the photo with two section:
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 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);
}
});
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),
}));
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);
}
}
i have to finish this to next week cause it's a project at school :(
You can customize the navigation drawer with the proper layout you need.
You can inflate any layout with in the drawer and make proper logic to implement.
You need to modify the method
onCreateView();
For a particular layout you can modify as -
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView= inflater.inflate(
R.layout.fragment_navigation_drawer_layout, container, false);
return rootView;
}
Here
fragment_navigation_drawer_layout
is the layout you want to set.

Adding icon in the default navigation drawer in Android Studio

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.

Android Navigation Drawer custom ListView not responding to Click

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

Categories

Resources