how can i add an image header to my navigation drawer layout like this one
and this is my code :
MainActivity.java
package com.webileapps.navdrawer;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.webileapps.navdrawer.House_Fragment.Garage_Fragment;
import com.webileapps.navdrawer.House_Fragment.Hall_Fragment;
import com.webileapps.navdrawer.House_Fragment.Kitchen_Fragment;
import com.webileapps.navdrawer.menu.Settings.AccountPreference;
import com.webileapps.navdrawer.menu.Settings.DialogChangeAccount;
import com.webileapps.navdrawer.menu.Settings.DialogChangeCity;
import com.webileapps.navdrawer.menu.Settings.DialogSettingsApp;
import com.webileapps.navdrawer.menu.Settings.DialogSupport;
import com.webileapps.navdrawer.menu.Settings.CityPreference;
import com.webileapps.navdrawer.menu.Settings.DialogueConnexion;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends SherlockFragmentActivity
implements DialogChangeCity.dialogDoneListenerCity,
DialogChangeAccount.dialogDoneListenerAccount,
DialogSettingsApp.dialogDoneListenerSett,
DialogSupport.dialogDoneListenerSupp,
DialogueConnexion.dialogDoneListenerConn {
DrawerLayout mDrawerLayout;
DrawerLayout mDrawerLayoutR;
ExpandableListView mDrawerList;
ExpandableListView mDrawerListR;
ActionBarDrawerToggle mDrawerToggle;
ActionBarDrawerToggle mDrawerToggleR;
private CharSequence mDrawerTitle;
private CharSequence mDrawerTitleR;
private CharSequence mTitle;
private CharSequence mTitleR;
List<Model> listDataHeader;
List<Model> listDataHeaderR;
HashMap<Model, List<Model>> listDataChild;
ExpandableListAdapter listAdapter;
ExpandableListAdapter listAdapterR;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mTitleR = mDrawerTitleR = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ExpandableListView) findViewById(R.id.left_drawer);
mDrawerListR = (ExpandableListView) findViewById(R.id.right_drawer);
prepareListData();
prepareListDataRight();
// set a custom shadow that overlays
the main content when the drawer opens
listAdapter = new ExpandableListAdapter(this,
listDataHeader, listDataChild);
listAdapterR = new ExpandableListAdapter(this, listDataHeaderR,null);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// mDrawerLayout.setDrawerShadow(R.drawable.up_24,GravityCompat.END);
// set up the drawer's list view with items and click listener
/* mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mRoomTitles));*/
mDrawerList.setAdapter(listAdapter);
mDrawerListR.setAdapter(listAdapterR);
//mDrawerList.setOnItemClickListener(
new DrawerItemClickListener());
mDrawerListR.setOnGroupClickListener(new ExpandableListView.
OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView expandable
ListView,
View view, int i, long l) {
switch(i){
case 0:
DialogSettingsApp dialogSettingsApp =
new DialogSettingsApp();
dialogSettingsApp.
show(getFragmentManager(),"diagSett");
break;
case 1:
DialogChangeAccount dialogChangeAccount =
new DialogChangeAccount();
dialogChangeAccount.
show(getFragmentManager(),"diagA");
break;
case 2:
DialogChangeCity dialogChangeCity =
new DialogChangeCity();
dialogChangeCity.show(getFragmentManager(),"diagC");
break;
case 3:
DialogSupport dialogSupport = new DialogSupport();
dialogSupport.show(getFragmentManager(),"diagSupp");
break;
case 4:
DialogueConnexion dialogueConnexion =
new DialogueConnexion();
dialogueConnexion.
show(getFragmentManager(),"diagConn");
break;
}
return false;
}
});
mDrawerList.setOnGroupClickListener(new ExpandableListView.
OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
Fragment frg = null;
switch (groupPosition) {
case 0:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content, PageSlidingHomeFragment.newInstance()
, PageSlidingHomeFragment.TAG).commit();
mDrawerList.setItemChecked(groupPosition, true);
mDrawerList.setSelection(groupPosition);
mDrawerLayout.closeDrawer(mDrawerList);
break;
case 1:
break;
case 2:
frg = new Kitchen_Fragment();
break;
case 3:
frg = new Garage_Fragment();
break;
case 4:
frg = new Hall_Fragment();
break;
}
if (frg != null) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.content, frg).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(groupPosition, true);
mDrawerList.setSelection(groupPosition);
mDrawerLayout.closeDrawer(mDrawerList);
}
return false;
}
});
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggleR=new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.down_24,
R.string.drawer_open,
R.string.drawer_close
){
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitleR);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /*
nav drawer image to replace 'Up' caret */
R.string.drawer_open, /*
"open drawer" description for accessibility */
R.string.drawer_close /*
"close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.setDrawerListener(mDrawerToggleR);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu){
com.actionbarsherlock.view.MenuInflater
inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
mDrawerLayout.closeDrawer(mDrawerListR);
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
break;
}
case R.id.action_contact:{
mDrawerLayout.closeDrawer(mDrawerList);
if (mDrawerLayout.isDrawerOpen(mDrawerListR)) {
mDrawerLayout.closeDrawer(mDrawerListR);
} else {
mDrawerLayout.openDrawer(mDrawerListR);
}
break;
}
}
return super.onOptionsItemSelected(item);
}
public void showInputDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Change city");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("Go", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
changeCity(input.getText().toString());
}
});
builder.show();
}
public void changeCity(String city) {
new CityPreference(this).setCity(city);
}
// The click listener for ListView in the navigation drawer
/*private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view
, int position,long id) {
selectItem(position);
}
}
*/
#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);
}
private void selectItem(int position) {
switch (position) {
case 0:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content,
PageSlidingHomeFragment.newInstance(),
PageSlidingHomeFragment.TAG).commit();
break;
}
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
private void prepareListDataRight(){
listDataHeaderR = new ArrayList<Model>();
listDataHeaderR.add(new Model(R.drawable.settings_24,
"App Settings"));
listDataHeaderR.add(new Model(R.drawable.edit_user_24,
"Update Account"));
listDataHeaderR.add(new Model(R.drawable.edit_24, "Change City"));
listDataHeaderR.add(new Model(R.drawable.quest_24, "Support"));
listDataHeaderR.add(new Model(R.drawable.
ic_action_user, "Disconnection"));
}
private void prepareListData() {
listDataHeader = new ArrayList<Model>();
listDataChild = new HashMap<Model, List<Model>>();
// Adding child data
listDataHeader.add(new Model(R.drawable.home24, "Home"));
listDataHeader.add(new Model("Rooms"));
listDataHeader.add(new Model(R.drawable.kitchen_24, "Kitchen"));
listDataHeader.add(new Model(R.drawable.garage_24, "Garage"));
listDataHeader.add(new Model(R.drawable.room_24, "Hall"));
// Adding child data
List<Model> home = new ArrayList<Model>();
home.add(new Model(R.drawable.settings_24, "Settings"));
home.add(new Model(R.drawable.devices_24, "Devices"));
home.add(new Model(R.drawable.weather_24, "Weather"));
List<Model> rooms = new ArrayList<Model>();
rooms.add(new Model(R.drawable.bed_c_24, "1sr Child room"));
rooms.add(new Model(R.drawable.bed_c_24, "2sd Child room"));
rooms.add(new Model(R.drawable.bedroom_24, "Parents room"));
rooms.add(new Model(R.drawable.hotel_24, "Guests room"));
rooms.add(new Model(R.drawable.dining_room_24, "Dining room"));
rooms.add(new Model(R.drawable.livingroom_24, "Living room"));
rooms.add(new Model(R.drawable.office_24, "Office"));
rooms.add(new Model(R.drawable.bathroom_24, "Bathroom 1st floor"));
rooms.add(new Model(R.drawable.bathroom_24, "Bathroom 2nd floor"));
// Header, Child data
listDataChild.put(listDataHeader.get(1), rooms);
}
#Override
public void onDone(String text, boolean state) {
if (state) {
changeCity(text);
//this.recreate();
restartSelf();
}
}
private void restartSelf() {
AlarmManager am = (AlarmManager) gettSystemService(Context.
ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,Calendar.getInstance()
.getTimeInMillis()
+ 1000, // one second
PendingIntent.getActivity(this, 0, getIntent(),
PendingIntent.FLAG_ONE_SHOT
| PendingIntent.FLAG_CANCEL_CURRENT));
finish();
}
#Override
public void onDoneA(String login, String opwd, String npwd) {
if(login!="" && opwd!="" && npwd!=""){
changeAccount(login,opwd,npwd);
}
}
private void changeAccount(String login, String opwd, String npwd) {
new AccountPreference(this).setAccountL(login);
new AccountPreference(this).setAccountOP(opwd);
new AccountPreference(this).setAccountNP(npwd);
}
#Override
public void onDone() {
int x = 0;
}
}
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas
.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<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:layout_width="match_parent" android:id="#+id/content"
android:layout_height="match_parent" >
</RelativeLayout>
<!-- The navigation drawer -->
<ExpandableListView
android:id="#+id/left_drawer"
android:layout_width="300dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#000"
android:choiceMode="singleChoice"
android:divider="#color/abs__bright_foreground_disabled_holo_dark"
android:dividerHeight="2dp" />
<ExpandableListView
android:id="#+id/right_drawer"
android:layout_width="200dp"
android:layout_height="300dp"
android:layout_gravity="end"
android:background="#000"
android:choiceMode="singleChoice"
android:divider="#color/abs__bright_foreground_disabled_holo_dark"
android:dividerHeight="2dp" />
</android.support.v4.widget.DrawerLayout>
ExpandableListAdapter.java
package com.webileapps.navdrawer;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context _context;
private List<Model> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<Model, List<Model>> _listDataChild;
public ExpandableListAdapter(Context context, List<Model> listDataHeader,
HashMap<Model, List<Model>> listChildData) {
this._context = context;
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 Model childText = (Model) 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);
ImageView IconListChild = (ImageView) convertView.findViewById
(R.id.item_icon_child);
IconListChild.setImageResource(childText.getIcon());
txtListChild.setText(childText.getTitle());
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
int i=0;
switch (groupPosition) {
case 1:
i= this._listDataChild.get
(this._listDataHeader.get(groupPosition)).size();
break;
default:
i=0;
break;
}
return i;
}
#Override
public Model 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) {
Model headerTitle = (Model) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
ImageView IconListHeader = (ImageView) convertView.findViewById
(R.id.item_icon_group);
IconListHeader.setImageResource(headerTitle.getIcon());
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle.getTitle());
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
In the Navigation Drawer layout xml file. Above drawerView and inside your parent layout add an image view as shown below:
<ImageView
android:id="#+id/image"
android:layout_width="280dp"
android:layout_height="140dp"
android:src="respective_source_of_image" />
This should be sufficient. Hope this helps.
Use Recycler View to create a navigation drawer. Recycler view is used most now. In your navigation drawer fragment have your layout file as shown below. This make you achieve your objective:
<RelativeLayout 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"
tools:context="com.ms.t.tms.NavigationDrawerFragment">
<ImageView
android:id="#+id/image"
android:layout_width="280dp"
android:layout_height="140dp"
android:src="respective_image_src" />
<android.support.v7.widget.RecyclerView
android:id="#+id/drawerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/image"
android:background="#color/colorPrimary"></android.support.v7.widget.RecyclerView>
</RelativeLayout>
You can simply do it following this sample :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- insert you main view childs here -->
</FrameLayout>
<!-- The navigation drawer -->
<LinearLayout
android:layout_width="240dp"
android:layout_gravity="end"
android:background="#color/colorPrimary"
android:orientation="vertical"
android:layout_height="match_parent">
<ImageView
android:layout_width="240dp"
android:layout_height="140dp"
android:src="#drawable/logo" />
<ListView
android:id="#+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="end"
android:choiceMode="singleChoice"
android:background="#color/colorPrimary"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
You will have your image added before the listview. You can manage your view like any other view.
Hope it will help you ;)
Related
I have used navigation slider menu for side menu screen But unable to get on click particular item in list.I am adding my code. When i am click on the side menu'content it should be open another screen . But unable to open other screen.
For a Example : If i am clicking on profile. it is not opening profile screen. & drawerlayout closes without opening screen.
See image of side menu's content
MainActivity
import android.app.ActionBar;
import android.app.Activity;
import android.supoort.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import info.androidhive.customlistviewvolley.adater.CustomListAdapter;
import info.androidhive.customlistviewvolley.adater.NavDrawerListAdapter;
import info.androidhive.customlistviewvolley.app.AppController;
import info.androidhive.customlistviewvolley.model.About;
import info.androidhive.customlistviewvolley.model.CurrencyConverter;
import info.androidhive.customlistviewvolley.model.EMICalculator;
import info.androidhive.customlistviewvolley.model.Feedback;
import info.androidhive.customlistviewvolley.model.Movie;
import info.androidhive.customlistviewvolley.model.NavDrawerItem;
import info.androidhive.customlistviewvolley.model.PayInstallment;
import info.androidhive.customlistviewvolley.model.Profile;
import info.androidhive.customlistviewvolley.model.Settings;
import info.androidhive.customlistviewvolley.model.SocialFeed;
public class MainActivity extends android.support.v4.app.FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adater ;
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// data of json url
private static final String url = "http://milagro.in/wip/apps/n/THDC2.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
//mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
//actionBar.setDisplayHomeAsUpEnabled(true);
listView = (ListView) findViewById(R.id.list);
adapter = new CustomListAdapter(this, movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
mTitle = mDrawerTitle = getTitle();
// 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);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Profile
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// About
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Emi Calculator
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Currency Converter
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// PayInstallments/EMI
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// Social Feed
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// Feedback
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
//Settings
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adater= new NavDrawerListAdapter(getApplicationContext(),navDrawerItems);
mDrawerList.setAdapter(adater);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.menu, //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) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
mDrawerList.bringToFront();
mDrawerLayout.requestLayout();
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
//displayView(1);
}
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setTitle(obj.getString("tata_project_name"));
movie.setThumbnailUrl(obj.getString("project_logo_url"));
movie.setParkingUrl(obj.getString("parking"));
movie.setPowerbackupUrl(obj.getString("powerbackup"));
movie.setFitnessUrl(obj.getString("fitness"));
movie.setLiftUrl(obj.getString("lift"));
movie.setParkUrl(obj.getString("park"));
movie.setSecurityUrl(obj.getString("security"));
movie.setSwimmingUrl(obj.getString("swimming"));
movie.setTypology(obj.getString("project_Typology"));
movie.setPrice(obj.getString("price"));
// adding movie to movies array
movieList.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
private class SlideMenuClickListener implements
AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Log.e("MainActivity", "Error in creating fragment");
//display view for selected nav drawer item
displayView(position);
Log.e("MainActivity", "Error in creating fragment12");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
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);
}
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Profile();
break;
case 1:
fragment = new About();
break;
case 2:
fragment = new EMICalculator();
break;
case 3:
fragment = new CurrencyConverter();
break;
case 4:
fragment = new PayInstallment();
break;
case 5:
fragment = new SocialFeed();
break;
case 6 :
fragment =new Feedback();
break;
case 7:
fragment =new Settings();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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);
}
public void bottomMenuClick(View v)
{
int pos = Integer.parseInt(v.getTag().toString());
switch (pos)
{
case 1: // enquiry screen
startActivity(new Intent(MainActivity.this,Enquiry.class));
break;
case 2: // contact screen
startActivity(new Intent(MainActivity.this, Contact.class));
break;
case 3: // Instant Call Back screen
startActivity(new Intent(MainActivity.this, CallBack.class));
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
activity_main
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_row_selector"
android:background="#color/list_background"/>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
Navdrawerlistadapter.java
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(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) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
}
Navdraweritem
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(){}
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;
}
}
Profile(1st content of side menu ) which is not opening after click.
public class Profile extends Fragment {
public Profile(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.profile, container, false);
return rootView;
}
}
profile.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="match_parent">
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="16dp"
android:text="Profile"/>
</RelativeLayout>
Ok, your problem will be solved here.
You should add these lines:
mDrawerList.bringToFront();
mDrawerLayout.requestLayout();
Also please note that SlideMenuClickListener should implement AdapterView.OnItemClickListener, not ListView.OnItemClickListener.
For future, please consider using NavigationView instead - it's also highly customizable and much easier, as for me.
Update. As you use support drawer, please try to
android.support.v4.app.Fragment;
android.support.v4.app.FragmentManager;
And use then getSupportFragmentManager().
I believe it should work.
Update2. Try to do like here:
remove ListView with #+id/list from main layout, leave there only frame_container and list_slidermenu.
Update3.
Make xml for fragment:
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
Make class for fragment:
public class NewFragment extends Fragment {
public NewFragment (){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.new_fragment, container, false);
ListView list = (Listview) rootView.findViewById(R.id.list);
//then do what you need with this list
return rootView;
}
}
In MainActivity replace container with instance of your NewFragment.
activity_main.xml should be like this
Because of Framelayout tag is a container and must contain the json data listview
<RelativeLayout 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"
tools:context=".MainActivity"
android:id="#+id/app_name"
>
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_row_selector"
android:background="#color/list_background"/>
</FrameLayout>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
I have a menu defined in xml:
<group android:checkableBehavior="single" android:id="#+id/group">
<item
android:id="#+id/grades"
android:icon="#drawable/ic_font_download_black_48dp"
android:checked="false"
android:title="Grades" >
<menu>
<item
android:id="#+id/mp1"
android:icon="#drawable/ic_looks_one_black_24dp"
android:checked="false"
android:title="MP1" />
<item
android:id="#+id/mp2"
android:icon="#drawable/ic_looks_two_black_24dp"
android:checked="false"
android:title="MP2" />
<item
android:id="#+id/mp3"
android:icon="#drawable/ic_font_download_black_48dp"
android:checked="false"
android:title="MP3" />
<item
android:id="#+id/mp4"
android:icon="#drawable/ic_font_download_black_48dp"
android:checked="false"
android:title="MP4" />
</menu>
</item>
<item
android:id="#+id/schedule"
android:icon="#drawable/ic_event_black_48dp"
android:checked="false"
android:title="Schedule" />
<item
android:id="#+id/attendance"
android:icon="#drawable/ic_assignment_ind_black_48dp"
android:checked="false"
android:title="Attendance" />
<item
android:id="#+id/assignments"
android:icon="#drawable/ic_assignment_black_48dp"
android:checked="false"
android:title="Assignments" />
<item
android:id="#+id/studentInfo"
android:icon="#drawable/ic_account_circle_black_48dp"
android:checked="false"
android:title="Student Details" />
</group>
<group android:id="#+id/group2" android:checkableBehavior="single">
<item
android:id="#+id/placeholder"
android:icon="#drawable/ic_android_black_48dp"
android:checked="false"
android:title="Placeholder" />
<item
android:id="#+id/placeholder2"
android:icon="#drawable/ic_android_black_48dp"
android:checked="false"
android:title="Placeholder" />
</group>
which adds a submenu which looks like this:
However, I am unable to make this submenu look like this: (collapsable)
I now know that I need to implement an expandableListView, but I am not sure how this would fit in with the menu I have already created.
Any advice is appreciated
You can create it using custom ListView.
See the code below activity_navigation_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true">
<ExpandableListView
android:id="#+id/navigationmenu"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginTop="192dp"
android:background="#android:color/white">
</ExpandableListView>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
The adapter for expandable list view is as follows.
ExpandableListAdapter.java
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private List<ExpandedMenuModel> mListDataHeader; // header titles
// child data in format of header title, child title
private HashMap<ExpandedMenuModel, List<String>> mListDataChild;
ExpandableListView expandList;
public ExpandableListAdapter(Context context, List<ExpandedMenuModel> listDataHeader, HashMap<ExpandedMenuModel, List<String>> listChildData, ExpandableListView mView) {
this.mContext = context;
this.mListDataHeader = listDataHeader;
this.mListDataChild = listChildData;
this.expandList = mView;
}
#Override
public int getGroupCount() {
int i = mListDataHeader.size();
Log.d("GROUPCOUNT", String.valueOf(i));
return this.mListDataHeader.size();
}
#Override
public int getChildrenCount(int groupPosition) {
int childCount = 0;
if (groupPosition != 2) {
childCount = this.mListDataChild.get(this.mListDataHeader.get(groupPosition))
.size();
}
return childCount;
}
#Override
public Object getGroup(int groupPosition) {
return this.mListDataHeader.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
Log.d("CHILD", mListDataChild.get(this.mListDataHeader.get(groupPosition))
.get(childPosition).toString());
return this.mListDataChild.get(this.mListDataHeader.get(groupPosition))
.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
ExpandedMenuModel headerTitle = (ExpandedMenuModel) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.listheader, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.submenu);
ImageView headerIcon = (ImageView) convertView.findViewById(R.id.iconimage);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle.getIconName());
headerIcon.setImageResource(headerTitle.getIconImg());
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_submenu, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.submenu);
txtListChild.setText(childText);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
list_submenu.xml is as follows.
<?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="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/submenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:padding="10dp"
android:textColor="#000000"
android:textSize="18sp"/>
</LinearLayout>
listheader.xml is as follows.
<?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="2dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="20dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/iconimage"
android:layout_width="50dp"
android:layout_height="50dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"/>
<TextView
android:id="#+id/submenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#000000"
android:textSize="20sp"/>
</LinearLayout>
</LinearLayout>
In your navigation view activity, set the adapter for the expandable list view.
NavigationViewActivity.java
public class NavigationViewActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
ExpandableListAdapter mMenuAdapter;
ExpandableListView expandableList;
List<ExpandedMenuModel> listDataHeader;
HashMap<ExpandedMenuModel, List<String>> listDataChild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_view);
final ActionBar ab = getSupportActionBar();
/* to set the menu icon image*/
ab.setHomeAsUpIndicator(android.R.drawable.ic_menu_add);
ab.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
expandableList = (ExpandableListView) findViewById(R.id.navigationmenu);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
prepareListData();
mMenuAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild, expandableList);
// setting list adapter
expandableList.setAdapter(mMenuAdapter);
expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
//Log.d("DEBUG", "submenu item clicked");
return false;
}
});
expandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
//Log.d("DEBUG", "heading clicked");
return false;
}
});
}
private void prepareListData() {
listDataHeader = new ArrayList<ExpandedMenuModel>();
listDataChild = new HashMap<ExpandedMenuModel, List<String>>();
ExpandedMenuModel item1 = new ExpandedMenuModel();
item1.setIconName("heading1");
item1.setIconImg(android.R.drawable.ic_delete);
// Adding data header
listDataHeader.add(item1);
ExpandedMenuModel item2 = new ExpandedMenuModel();
item2.setIconName("heading2");
item2.setIconImg(android.R.drawable.ic_delete);
listDataHeader.add(item2);
ExpandedMenuModel item3 = new ExpandedMenuModel();
item3.setIconName("heading3");
item3.setIconImg(android.R.drawable.ic_delete);
listDataHeader.add(item3);
// Adding child data
List<String> heading1 = new ArrayList<String>();
heading1.add("Submenu of item 1");
List<String> heading2 = new ArrayList<String>();
heading2.add("Submenu of item 2");
heading2.add("Submenu of item 2");
heading2.add("Submenu of item 2");
listDataChild.put(listDataHeader.get(0), heading1);// Header, Child data
listDataChild.put(listDataHeader.get(1), heading2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupDrawerContent(NavigationView navigationView) {
//revision: this don't works, use setOnChildClickListener() and setOnGroupClickListener() above instead
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
}
ExpandedMenuModel class contains menu item details as follow.
ExpandedMenuModel.java
public class ExpandedMenuModel {
String iconName = "";
int iconImg = -1; // menu icon resource id
public String getIconName() {
return iconName;
}
public void setIconName(String iconName) {
this.iconName = iconName;
}
public int getIconImg() {
return iconImg;
}
public void setIconImg(int iconImg) {
this.iconImg = iconImg;
}
}
[Side note]:
Don't put import android.widget.ExpandableListAdapter; in NavigationViewActivity.java. This mistake can happen if you resolve import by Alt+Enter before create the file ExpandableListAdapter.java.
Put compile 'com.android.support:design:23.3.0' in app's build.gradle, it's for "NavigationView" and its "import android.support.design.widget.NavigationView;" After that (Might require rebuild first) you can do Alt-Enter to resolve import.
The file hierarchy should look like (3 .java and 3 .xml from above):
The output screenshot:
MainActivity.java
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ExpandableListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
View view_Group;
private DrawerLayout mDrawerLayout;
ExpandableListAdapter mMenuAdapter;
ExpandableListView expandableList;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
//Icons, use as you want
static int[] icon = { R.drawable.ico1, R.drawable.ico1,
R.drawable.ico1, R.drawable.ico1,
R.drawable.ico1, R.drawable.ico1, R.drawable.ico1};
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
expandableList.setIndicatorBounds(expandableList.getRight()- 80, expandableList.getWidth());
} else {
expandableList.setIndicatorBoundsRelative(expandableList.getRight()- 80, expandableList.getWidth());
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
expandableList = (ExpandableListView) findViewById(R.id.navigationmenu);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
if (navigationView != null) {
setupDrawerContent(navigationView);
}
prepareListData();
mMenuAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expandableList.setAdapter(mMenuAdapter);
expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView expandableListView,
View view,
int groupPosition,
int childPosition, long id) {
//Log.d("DEBUG", "submenu item clicked");
Toast.makeText(MainActivity.this,
"Header: "+String.valueOf(groupPosition) +
"\nItem: "+ String.valueOf(childPosition), Toast.LENGTH_SHORT)
.show();
view.setSelected(true);
if (view_Group != null) {
view_Group.setBackgroundColor(Color.parseColor("#ffffff"));
}
view_Group = view;
view_Group.setBackgroundColor(Color.parseColor("#DDDDDD"));
mDrawerLayout.closeDrawers();
return false;
}
});
expandableList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
//Log.d("DEBUG", "heading clicked");
return false;
}
});
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding data header
listDataHeader.add("menu1");
listDataHeader.add("menu2");
listDataHeader.add("menu3");
listDataHeader.add("menu4");
listDataHeader.add("menu5");
listDataHeader.add("menu6");
listDataHeader.add("menu7");
// Adding child data
List<String> heading1 = new ArrayList<String>();
heading1.add("Submenu");
heading1.add("Submenu");
heading1.add("Submenu");
List<String> heading2 = new ArrayList<String>();
heading2.add("Submenu");
heading2.add("Submenu");
heading2.add("Submenu");
heading2.add("Submenu");
List<String> heading3 = new ArrayList<String>();
heading3.add("Submenu");
heading3.add("Submenu");
List<String> heading4 = new ArrayList<String>();
heading4.add("Submenu");
heading4.add("Submenu");
List<String> heading5 = new ArrayList<String>();
heading5.add("Submenu");
heading5.add("Submenu");
heading5.add("Submenu");
List<String> heading6 = new ArrayList<String>();
heading6.add("Submenu");
heading6.add("Submenu");
List<String> heading7 = new ArrayList<String>();
heading4.add("Submenu");
heading4.add("Submenu");
listDataChild.put(listDataHeader.get(0), heading1);// Header, Child data
listDataChild.put(listDataHeader.get(1), heading2);
listDataChild.put(listDataHeader.get(2), heading3);
listDataChild.put(listDataHeader.get(3), heading4);
listDataChild.put(listDataHeader.get(4), heading5);
listDataChild.put(listDataHeader.get(5), heading6);
listDataChild.put(listDataHeader.get(6), heading7);
}
private void setupDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
/*if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}*/
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
ExpandableListAdapter.java
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/1/16.
*/
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private List<String> mListDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> mListDataChild;
ExpandableListView expandList;
public ExpandableListAdapter(Context context,
List<String> listDataHeader,
HashMap<String,
List<String>> listChildData
// ,ExpandableListView mView
)
{
this.mContext = context;
this.mListDataHeader = listDataHeader;
this.mListDataChild = listChildData;
//this.expandList = mView;
}
#Override
public int getGroupCount() {
int i = mListDataHeader.size();
//Log.d("GROUPCOUNT", String.valueOf(i));
return i;
}
#Override
public int getChildrenCount(int groupPosition) {
return this.mListDataChild.get(
this.mListDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this.mListDataHeader.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
//Log.d("CHILD", mListDataChild.get(this.mListDataHeader.get(groupPosition))
// .get(childPosition).toString());
return this.mListDataChild.get(
this.mListDataHeader.get(groupPosition))
.get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.listheader, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.submenu);
ImageView headerIcon = (ImageView) convertView.findViewById(R.id.iconimage);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
//lblListHeader.setText(headerTitle.getIconName());
headerIcon.setImageResource(MainActivity.icon[groupPosition]);
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_submenu, null);
}
TextView txtListChild = (TextView) convertView
.findViewById(R.id.submenu);
txtListChild.setText(childText);
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
list_submenu.xml
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="#000000"
android:layout_marginLeft="44dp"
android:textSize="14sp"
android:id="#+id/submenu"/>
</LinearLayout>
listheader.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="2dp"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="45dp"
android:layout_height="45dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:id="#+id/iconimage"/>
<TextView
android:layout_width="match_parent"
android:layout_height="45dp"
android:padding="10dp"
android:textColor="#000000"
android:textSize="16sp"
android:id="#+id/submenu"
android:gravity="center_vertical" />
</LinearLayout>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main">
<ExpandableListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"
android:layout_marginTop="160dp"
android:choiceMode="singleChoice"
android:id="#+id/navigationmenu">
</ExpandableListView>
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
Hope this will work and some other files are in this example... I think you can solve those matters... It will look like as you are wanted...
You can follow Priyank Patel answer above. Additionally, I wanted to hide the drop-down icon in front of the list item.
Just add android:groupIndicator="#null" to your ExpandableListView in xml tag.
<ExpandableListView
android:id="#+id/navigationmenu"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:groupIndicator="#null"
android:layout_marginTop="192dp"
android:background="#android:color/white">
</ExpandableListView>
You can do it by simple way without ExpandableListView
1- for showing down arrow u can customize menu item by actionLayout,
also I'm giving unique id for each group to show divider line
**Media has 3 sub items
<item
android:id="#+id/nav_media"
android:title="Media"
app:actionLayout="#layout/nav_arrow" />
<group
android:id="#+id/media_group"
android:checkableBehavior="single"
android:visible="false">
<item
android:title="Media1"
app:actionLayout="#layout/nav_arrow"
/>
<item
android:title="Media2"
app:actionLayout="#layout/nav_arrow"
/>
<item
android:title="Media3"
app:actionLayout="#layout/nav_arrow"
/>
</group>
2- this is nav_arrow.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:id="#+id/igv_arrow"
android:layout_width="15dp"
android:layout_height="15dp"
android:layout_marginStart="5dp"
android:gravity="center"
android:layout_marginTop="16dp"
android:layout_marginBottom="16dp"
android:src="#drawable/ic_16_arrow_right"/>
</LinearLayout>
3- then in Activity
private boolean isMediaVisible= false;
case R.id.nav_media:
if (!isMediaVisible) {
menuItemArrow.setRotation(90f);//to rotating arrow to down
navigationView.getMenu().setGroupVisible(R.id.media_group, true);
isMediaVisible= true;
} else {
menuItemArrow.setRotation(0f);
navigationView.getMenu().setGroupVisible(R.id.media_group, false);
isMediaVisible= false;
}
return;
Thanks #Priyank and #atabek it relay helped me
when i completed this code it was working fine except the item click event and it was not showing selected item for that i made a small changes
in layout ExpandableListView i have added listSelector (http://developer.android.com/reference/android/widget/AbsListView.html#attr_android:listSelector)
<ExpandableListView
android:id="#+id/navigationmenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="192dp"
android:background="#android:color/white"
android:choiceMode="singleChoice"
android:listSelector="#color/colorAccent"
/>
and in activity instead of setting up the click listener to NavigationView changed to expandableList (http://developer.android.com/reference/android/widget/ExpandableListView.OnChildClickListener.html)
------
------
private void setupDrawerContent(NavigationView navigationView) {
expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
int index = parent.getFlatListPosition(ExpandableListView.getPackedPositionForChild(groupPosition, childPosition));
parent.setItemChecked(index, true);
Toast.makeText(MainActivity.this, "clicked " + listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition).toString(), Toast.LENGTH_SHORT).show();
mDrawerLayout.closeDrawers();
return true;
}
});
/*
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
return true;
}
});
*/
}
------
------
I want to display the child items of its respective group item available in expandable listview into seperate listview.
I have done the following,
package com.example.demo_data1;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.Toast;
#SuppressLint("NewApi")
public class DrawerLayoutTest extends Activity implements OnChildClickListener {
private DrawerLayout drawer;
private ExpandableListView drawerList;
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_layout_test);
setGroupData();
setChildGroupData();
initDrawer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.drawer_layout_test, menu);
return true;
}
private void initDrawer() {
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ExpandableListView) findViewById(R.id.left_drawer);
drawerList.setAdapter(new NewAdapter(this, groupItem, childItem));
drawerList.setOnChildClickListener(this);
// actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer,
// R.drawable.ic_drawer, R.string.open_drawer,
// R.string.close_drawer) {
// public void onDrawerClosed(View view) {
// getActionBar().setSubtitle("open");
// }
//
// /** Called when a drawer has settled in a completely open state. */
// public void onDrawerOpened(View drawerView) {
// getActionBar().setSubtitle("close");
// }
//
// };
//
// drawer.setDrawerListener(actionBarDrawerToggle);
}
public void setGroupData() {
groupItem.add("TECHNOLOGY");
groupItem.add("MOBILE");
groupItem.add("MANUFACTURER");
groupItem.add("EXTRAS");
}
ArrayList<String> groupItem = new ArrayList<String>();
ArrayList<Object> childItem = new ArrayList<Object>();
public void setChildGroupData() {
/**
* Add Data For TecthNology
*/
ArrayList<String> child = new ArrayList<String>();
child.add("Java");
child.add("Drupal");
child.add(".Net Framework");
child.add("PHP");
childItem.add(child);
/**
* Add Data For Mobile
*/
child = new ArrayList<String>();
child.add("Android");
child.add("Window Mobile");
child.add("iPHone");
child.add("Blackberry");
childItem.add(child);
/**
* Add Data For Manufacture
*/
child = new ArrayList<String>();
child.add("HTC");
child.add("Apple");
child.add("Samsung");
child.add("Nokia");
childItem.add(child);
/**
* Add Data For Extras
*/
child = new ArrayList<String>();
child.add("Contact Us");
child.add("About Us");
child.add("Location");
child.add("Root Cause");
childItem.add(child);
}
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
switch (groupPosition)
{
case 0:
switch (childPosition)
{
case 0:
MainActivity();
break;
case 1:
//
}
}
return false;
}
private void MainActivity(){
Intent myIntent = new Intent(this, MainActivity.class);
startActivity(myIntent);
}
}
Now here in the above code the child items are getting displayed below the group item in same listview instead i want to display the child items in different listview next to group item listview.
Please help me with this, stuck from a long time.
Any help regarding this will be appreciated.
use this code
activity_main.xml
<LinearLayout 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:baselineAligned="false"
android:orientation="vertical"
tools:context="com.example.listtest.MainActivity" >
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<!-- Drawer Content -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<!-- The navigation menu -->
<ListView
android:id="#+id/left_drawer_child"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:layout_gravity="start"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#android:color/white" />
</android.support.v4.widget.DrawerLayout>
MainActivity.java
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
Fragment fragment = null;
ListView mainlist;
ArrayList<String> formain = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainlist = (ListView) findViewById(R.id.left_drawer_child);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setScrimColor(getResources().getColor(android.R.color.transparent));
mDrawerLayout.setDrawerListener(mDrawerListener);
// childlist = (ListView) findViewById(R.id.listView2);
formain.add("TECHNOLOGY");
formain.add("MOBILE");
formain.add("MANUFACTURER");
formain.add("EXTRAS");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,formain);
mainlist.setAdapter(adapter);
mDrawerLayout.openDrawer(mainlist);
mainlist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
String getGroup = formain.get(arg2);
if (getGroup == "TECHNOLOGY"){
fragment = new TechnologyFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerLayout.closeDrawer(mainlist);
}
if (getGroup == "MOBILE"){
//fragment for mobile
}
if (getGroup == "MANUFACTURER"){
//fragment for manufacturer
}
if (getGroup == "EXTRAS"){
//fragment for extras
}
}
});
}
private DrawerListener mDrawerListener = new DrawerListener() {
#Override
public void onDrawerStateChanged(int status) {
}
#Override
public void onDrawerSlide(View view, float slideArg) {
}
#Override
public void onDrawerOpened(View view) {
}
#Override
public void onDrawerClosed(View view) {
}
};
}
technology_fragment.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
TechnologyFragment.java
public class TechnologyFragment extends Fragment {
ListView techlist;
ArrayList<String> forchild = new ArrayList<String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
View rootView = inflater.inflate(R.layout.technology_fragment, null);
techlist = (ListView) rootView.findViewById(R.id.listView1);
forchild.add("Java");
forchild.add("Drupal");
forchild.add(".Net Framework");
forchild.add("PHP");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,forchild);
techlist.setAdapter(adapter);
return rootView;
}
}
Instead of using a ExpandableListView make use of a Normal ListView and fragments.
Show the parent List in Fragment 1 and clicking an item in parent 1 will show fragment 2 which has Child items in a list.
I am trying to change the TextViews in ActionBarSherlock Navigation drawer to EditTexts with hints.
so far i have accomplished to create edit texts from it (which was piece a cake) but i cannot seem to find out how to create a Hint from the text, it appears as filled in editTexts now..
how can i change it?
Below is my code.
As i do not know which part is relevant, i post a lot of code.
mFragmentTitles = getResources().getStringArray(R.array.nav_drawer_items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mDrawerList = (ListView)findViewById(R.id.drawer_list);
//mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mFragmentTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View v){
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View v){
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(savedInstanceState == null){
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
}else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
case R.id.settings:
if(mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
}else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
selectItem(position);
}
}
private void selectItem(int position){
Fragment newFragment = new Fragment_1();
FragmentManager fm = getSupportFragmentManager();
switch(position){
case 0:
newFragment = new Fragment_1();
break;
case 1:
newFragment = new fragment_2();
break;
case 2:
newFragment = new fragment_3();
break;
case 3:
newFragment = new fragment_4();
break;
case 4:
newFragment = new Fragment_1();
break;
}
fm.beginTransaction()
.replace(R.id.content_frame, newFragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mFragmentTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title){
mTitle = title;
getSupportActionBar().setTitle(title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
In my Xml is an EditText (drawer_list_item.xml)
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center_vertical"
android:textColor="#fff"
android:minHeight="48dp"/>
and this is my other XML which i use to display the drawer.
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content_frame"/>
<ListView
android:id="#+id/drawer_list"
android:layout_width="240dp"
android:layout_height="match_parent"
android:divider="#0c7f58"
android:dividerHeight="1dp"
android:background="#13ca8c"
android:choiceMode="singleChoice"
android:layout_gravity="end"
android:paddingLeft="16dp"
android:paddingRight="16dp"
/>
</android.support.v4.widget.DrawerLayout>
An ArrayAdapter, by default, loads the string value of each item as the corresponding TextView's text. It's implementation of getView() is:
if (convertView == null) {
view = mInflater.inflate(resource, parent, false);
} else {
view = convertView;
}
<irrelevant stuff snipped>
T item = getItem(position);
if (item instanceof CharSequence) {
text.setText((CharSequence)item);
} else {
text.setText(item.toString());
}
If what you want to do is load the hint instead of the text, you should override this method. For example, as this:
EditText edit = (EditText)LayoutInflater.from(getContext()).inflate(R.layout.drawer_list_item);
edit.setHint(getItem(position).toString());
That will get the corresponding string as hint, instead of text.
the way to fix this is to create a custom MenuAdapter and put the edit texts in there.
mMenuAdapter = new MenuListAdapter(MainFragActivity.this, title);
mDrawerList.setAdapter(mMenuAdapter);
//In your main class put the above code, then in your custom class put the below code;
import com.actionbarsherlock.app.SherlockFragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MenuListAdapter extends BaseAdapter {
// Declare variables
Context context;
String[] mTitle;
String[] mSubTitle;
LayoutInflater inflater;
public MenuListAdapter(Context context, String[] title) {
this.context = context;
this.mTitle = title;
}
#Override
public int getCount() {
return mTitle.length;
}
#Override
public Object getItem(int position) {
return mTitle[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Declare Variables
EditText txtTitle;
TextView txtSubTitle;
ImageView imgIcon;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.drawer_list_item, parent, false);
// Locate the TextViews
txtTitle = (EditText)itemView.findViewById(R.id.title);
// Set the data
txtTitle.setHint(mTitle[position]);
txtTitle.setBackground(null);
return itemView;
}
}
I am currently working on an android app for 4.2.2 that uses the new NavigationDrawer. It works like a charm except for adding icons.
I found some sample code in which the List view becomes a Relative layout in which 2 parallel arrays are nested and rendered by an Array Adapter based on a menu model a way that they are synchronized, I think.
Here is the MainActivity:
package com.sorin.medisynced.main;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.sorin.medisynced.R;
import com.sorin.medisynced.filepickerio.FilepickerSaver;
import com.sorin.medisynced.filepickerio.FilepickerViewer;
import com.sorin.medisynced.qr.IntentIntegrator;
public class MediSyncedMainActivity extends Activity {
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private String[] menuItemsData;
private String[] menuItemsTools;
private ActionBarDrawerToggle mDrawerToggle;
private String[] menuItemsEmergency;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
mTitle = mDrawerTitle = getTitle();
// set click listener for list drawer
// mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
_initMenu();
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(getString(R.string.drawer_close));
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(getString(R.string.drawer_open));
invalidateOptionsMenu(); // creates call to
// onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// selectItem(0);
}
}
private void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
// Add First Header
mAdapter.addHeader(R.string.menu_data);
// Add first block
menuItemsData = getResources().getStringArray(R.array.menu_data);
String[] menuDataIcons = getResources().getStringArray(
R.array.data_menu_icons);
int dataIcons = 0;
for (String item : menuItemsData) {
int id_data_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_data_icon = getResources()
.getIdentifier(menuDataIcons[dataIcons], "drawable",
this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_data_title,
id_data_icon);
mAdapter.addItem(mItem);
dataIcons++;
}
// Add second header
mAdapter.addHeader(R.string.menu_tools);
// Add second block
menuItemsTools = getResources().getStringArray(R.array.menu_tools);
String[] menuToolsIcons = getResources().getStringArray(
R.array.tools_menu_icons);
int toolsIcons = 0;
for (String item : menuItemsTools) {
int id_tools_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_tools_icon = getResources().getIdentifier(
menuToolsIcons[toolsIcons], "drawable",
this.getPackageName());
// creating drawer menu model
NsMenuItemModel mItem = new NsMenuItemModel(id_tools_title,
id_tools_icon);
mAdapter.addItem(mItem);
toolsIcons++;
}
// Add third header
mAdapter.addHeader(R.string.menu_emergency);
// Add third block
menuItemsEmergency = getResources().getStringArray(
R.array.menu_emergency);
String[] menuEmerIcons = getResources().getStringArray(
R.array.emergency_menu_icons);
int emerIcons = 0;
for (String item : menuItemsEmergency) {
int id_emer_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_emer_icon = getResources()
.getIdentifier(menuEmerIcons[emerIcons], "drawable",
this.getPackageName());
// creating drawer menu model
NsMenuItemModel mItem = new NsMenuItemModel(id_emer_title,
id_emer_icon);
mAdapter.addItem(mItem);
emerIcons++;
}
mDrawerList = (ListView) findViewById(R.id.drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content
// view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_save).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
* The action bar home/up should open or close the drawer.
* ActionBarDrawerToggle will take care of this.
*/
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch (item.getItemId()) {
case R.id.action_qrscan:
IntentIntegrator integrator = new IntentIntegrator(
MediSyncedMainActivity.this);
integrator.initiateScan();
Toast.makeText(this, "Scan Qr Code", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_filepicker_save:
startActivity(new Intent(this, FilepickerSaver.class));
Toast.makeText(this, "Save data on cloud", Toast.LENGTH_SHORT)
.show();
return true;
case R.id.action_filepicker_view:
startActivity(new Intent(this, FilepickerViewer.class));
Toast.makeText(this, "View data from cloud", Toast.LENGTH_SHORT)
.show();
return true;
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_SEARCH);
intent.putExtra(SearchManager.QUERY, getApplicationContext()
.getDatabasePath(DROPBOX_SERVICE));
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.search_database,
Toast.LENGTH_LONG).show();
}
return true;
default:
// Handle your other action bar items...
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// Highlight the selected item, update the title, and close the
// drawer
// update selected item and title, then close the drawer
mDrawerList.getCount();
mDrawerList.setItemChecked(position, true);
String text = "menu click... should be implemented";
Toast.makeText(MediSyncedMainActivity.this, text, Toast.LENGTH_LONG)
.show();
mDrawerLayout.closeDrawer(mDrawerList);
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
}
Here is the menu model:
package com.sorin.medisynced.main;
public class NsMenuItemModel {
public int title;
public int iconRes;
public boolean isHeader;
public NsMenuItemModel(int title, int iconRes,boolean header) {
this.title = title;
this.iconRes = iconRes;
this.isHeader=header;
}
public NsMenuItemModel(int title, int iconRes) {
this(title,iconRes,false);
}
}
Here ist the ArrayAdapter implementation:
package com.sorin.medisynced.main;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.sorin.medisynced.R;
public class NsMenuAdapter extends ArrayAdapter<NsMenuItemModel> {
/*
* public NsMenuAdapter(Context context, int resource, int
* textViewResourceId, String[] objects) { super(context,
* R.layout.ns_menu_row, textViewResourceId, objects); }
*/
public NsMenuAdapter(Context context) {
super(context, 0);
}
public void addHeader(int title) {
add(new NsMenuItemModel(title, -1, true));
}
public void addItem(int title, int icon) {
add(new NsMenuItemModel(title, icon, false));
}
public void addItem(NsMenuItemModel itemModel) {
add(itemModel);
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
return getItem(position).isHeader ? 0 : 1;
}
#Override
public boolean isEnabled(int position) {
return !getItem(position).isHeader;
}
public static class ViewHolder {
public final TextView textHolder;
public final ImageView imageHolder;
public ViewHolder(TextView text1, ImageView image1) {
this.textHolder = text1;
this.imageHolder = image1;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
NsMenuItemModel item = getItem(position);
ViewHolder holder = null;
View view = convertView;
if (view == null) {
int layout = R.layout.ns_menu_row;
if (item.isHeader)
layout = R.layout.ns_menu_row_header;
view = LayoutInflater.from(getContext()).inflate(layout, null);
TextView text1 = (TextView) view.findViewById(R.id.menurow_title);
ImageView image1 = (ImageView) view.findViewById(R.id.menurow_icon);
view.setTag(new ViewHolder(text1, image1));
}
if (holder == null && view != null) {
Object tag = view.getTag();
if (tag instanceof ViewHolder) {
holder = (ViewHolder) tag;
}
}
if(item != null && holder != null)
{
if (holder.textHolder != null)
holder.textHolder.setText(item.title);
if (holder.imageHolder != null) {
if (item.iconRes > 0) {
holder.imageHolder.setVisibility(View.VISIBLE);
holder.imageHolder.setImageResource(item.iconRes);
} else {
holder.imageHolder.setVisibility(View.GONE);
}
}
}
return view;
}
}
The string-array xml:
<string-array name="menu_data">
<item>menu_data_patient_profile</item>
<item>menu_data_hospital_staff</item>
<item>menu_data_xray_results</item>
<item>menu_data_lab_results</item>
<item>menu_data_medical_supplies_index</item>
<item>menu_data_hospital_forms_index</item>
<item>menu_data_prescriptions_index</item>
<item>menu_data_illness_index</item>
<item>menu_data_drugs_index</item>
<item>menu_data_hospital_interactive_map</item>
</string-array>
<string-array name="menu_tools">
<item>menu_tools_ecg</item>
<item>menu_tools_pulse</item>
<item>menu_tools_microscope_feed</item>
<item>menu_tools_blood_pressure</item>
<item>menu_tools_temperature</item>
<item>menu_tools_radiation_levels</item>
<item>menu_tools_movement_log</item>
</string-array>
<string-array name="menu_emergency">
<item>menu_emergency_call_ambulance</item>
<item>menu_emergency_call_helicopter</item>
<item>menu_emergency_call_nurse</item>
<item>menu_emergency_call_doctor</item>
</string-array>
<array name="data_menu_icons">
<item>ic_patient_profile</item>
<item>ic_hospital_staff</item>
<item>ic_xray_results</item>
<item>ic_lab_results</item>
<item>ic_medical_supplies_index</item>
<item>ic_hospital_forms_index</item>
<item>ic_prescription_index</item>
<item>ic_illness_index</item>
<item>ic_drugs_index</item>
<item>ic_hospital_interactive_map</item>
</array>
<array name="tools_menu_icons">
<item>ic_ecg</item>
<item>ic_pulse</item>
<item>ic_microscope_feed</item>
<item>ic_blood_pressure</item>
<item>ic_body_temperature</item>
<item>ic_radiation_levels</item>
<item>ic_movement_logger</item>
</array>
<array name="emergency_menu_icons">
<item>ic_call_ambulance</item>
<item>ic_call_helicopter</item>
<item>ic_call_nurse</item>
<item>ic_call_doctor</item>
</array>
and the main layout:
<!-- The main content view -->
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MediSyncedMainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/drawer_text" />
</RelativeLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#DADADC"
android:choiceMode="singleChoice"
android:divider="#android:color/darker_gray"
android:dividerHeight="1dp"
android:showDividers="middle" />
How can I simplify the approach. Is there a way to use one array instead of such a complicated structure.
B.t.w. you can find my project on github under:
https://github.com/greenspand/MediSynced
It is a medical app, hence the name.
Thx y'all.
You can use a custom list view along with the list adapter to display the counter besides the list item in the drawer. And then add whatever code you want to your counter method.
Here's the code I implemented in my navigation drawer supported android app :
getter/setter methods class for the drawer :
package info.aea.drawer;
public class NavDrawerItem {
private String title;
private String tag;
private int icon;
private String count = "0";
// boolean to set visibility of the counter
private boolean isCounterVisible = false;
public NavDrawerItem(){}
public NavDrawerItem(String title, String tag, int icon){
this.title = title;
this.tag = tag;
this.icon = icon;
}
public NavDrawerItem(String title, String tag, int icon, boolean isCounterVisible, String count){
this.title = title;
this.tag = tag;
this.icon = icon;
this.isCounterVisible = isCounterVisible;
this.count = count;
}
public String getTitle(){
return this.title;
}
public String getTag(){
return this.tag;
}
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 setTag(String tag){
this.tag = tag;
}
public void setIcon(int icon){
this.icon = icon;
}
public void setCount(String count){
this.count = count;
}
public void setCounterVisibility(boolean isCounterVisible){
this.isCounterVisible = isCounterVisible;
}
}
This is the list adapter I used to display the list. check the display count method in the end :
package info.aea.drawer;
import info.aea.snippets.R;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(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) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtTag = (TextView) convertView.findViewById(R.id.tag);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
txtTag.setText(navDrawerItems.get(position).getTag());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
}
Corresponding list layout :
<?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="match_parent"
android:background="#drawable/list_selector">
<ImageView
android:id="#+id/icon"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:contentDescription="#string/desc_list_item_icon"
android:src="#drawable/ic_home"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#id/icon"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#color/list_item_title"
android:textStyle="bold"
android:gravity="center_vertical"
android:paddingRight="40dp"/>
<TextView android:id="#+id/counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/counter_bg"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="8dp"
android:textColor="#color/counter_text_color"/>
<TextView
android:id="#+id/tag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/icon"
android:layout_alignParentBottom="true"
android:layout_marginLeft="12dp"
android:textColor="#999967"
android:textSize="13sp"
android:textStyle="italic"
android:text="sample" />
</RelativeLayout>
and here's the main N-drawer class :
package info.aea.launch;
import info.aea.drawer.NavDrawerItem;
import info.aea.drawer.NavDrawerListAdapter;
import info.aea.snippets.R;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class LaunchActivity_NavDrawer extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private String[] navMenuTags;;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SnippetsDB_Helper logindb;
logindb=new SnippetsDB_Helper(this);
//logindb=logindb.open();
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// load slide menu tags
navMenuTags = getResources().getStringArray(R.array.nav_drawer_tags);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuTags[0], navMenuIcons.getResourceId(0, -1), true, "22" ));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuTags[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuTags[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuTags[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuTags[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuTags[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuTags[6], navMenuIcons.getResourceId(6, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuTags[7], navMenuIcons.getResourceId(7, -1), true, "22"));
// empty list
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuTags[8], navMenuIcons.getResourceId(8, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuTags[9], navMenuIcons.getResourceId(9, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[10], navMenuTags[10], navMenuIcons.getResourceId(10, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[11], navMenuTags[11], navMenuIcons.getResourceId(11, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[12], navMenuTags[12], navMenuIcons.getResourceId(12, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[13], navMenuTags[13], navMenuIcons.getResourceId(13, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[14], navMenuTags[14], navMenuIcons.getResourceId(14, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[15], navMenuTags[15], navMenuIcons.getResourceId(15, -1)));
// Recycle the typed array
navMenuIcons.recycle();
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
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
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) {
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
displayView(0);
}
}
/**
* Slide menu item click listener
* */
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) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
Toast.makeText(getApplicationContext(), "code", Toast.LENGTH_LONG).show();
// Create new fragment and transaction
Fragment newFragment = new Fragment_Java();
// consider using Java coding conventions (upper char class names!!!)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.frame_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
return true;
case R.id.item1:
Toast.makeText(getApplicationContext(), "send a suggestion", Toast.LENGTH_LONG).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(), "Meet developers", Toast.LENGTH_LONG).show();
return true;
case R.id.item3:
Toast.makeText(getApplicationContext(), "Rate this app", Toast.LENGTH_LONG).show();
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);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new Fragment_a();
break;
case 1:
fragment = new Fragment_b();
break;
case 2:
fragment = new Fragment_C();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#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);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent result) {
super.onActivityResult(requestCode, resultCode, result);
}
}
here's my layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/drawer_item_icon"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="10sp"
android:layout_marginRight="10sp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/drawer_item_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25sp"
android:paddingTop="8sp"
android:paddingBottom="8sp"
android:paddingLeft="15sp" />
</LinearLayout>
Simplest way I did it is this way:
1. Make this as your drawer xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tashan="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:orientation="horizontal"
android:padding="#dimen/spacing_small" >
<ImageView
android:id="#+id/drawer_item_icons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/spacing_small"
android:layout_marginStart="#dimen/spacing_small"
android:contentDescription="#string/test_string"/>
<TextView
android:id="#+id/drawer_item_labels"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/spacing_normal"
android:layout_marginStart="#dimen/spacing_small"
android:paddingLeft="#dimen/spacing_small"
android:paddingRight="#dimen/spacing_small"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#58585b" />
</LinearLayout>
2. Add these values to your 'dimens.xml'. Never hardcode values!
<dimen name="spacing_normal">16dp</dimen>
<dimen name="spacing_small">8dp</dimen>
3. For Icons array add this String Array to 'strings.xml
<string-array name="array_main_menu">
<item>#drawable/1</item>
<item>#drawable/2</item>
<item>#drawable/3</item>
<item>#drawable/4</item>
<item>#drawable/5</item>
</string-array>
4. In your Adapter access this array by using a Typed Array instance.
TypedArray typedArray=getResources().obtainTypedArray(R.array.array_main_menu);
5. Inside the getView of your adapter, set image to Imageview like this.
mIcon.setImageResource(typedArray.getResourceId(position, -1));
here mIcon is your ImageView.
With recent versions of Support Library, the easiest way is to use a NavigationView. Here is a nice tutorial, and here is the official documentation.
A NavigationView is included as second view in the DrawerLayout (instead of ListView from OP code), for example:
<android.support.design.widget.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="#menu/left_menu" />
Then, the menu should be populated with titles and icons, like (left_menu.xml):
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group
android:id="#+id/leftMenuId"
android:checkableBehavior="single">
<item
android:id="#+id/item1"
android:icon="#drawable/ic_zzblack_24dp"
android:title="Title1" />
<item
android:id="#+id/settings"
android:icon="#drawable/ic_settings_black_24dp"
android:title="Settings" />
</group>
</menu>
For more details, please refer to the first link.