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>
Related
I am trying to use the sliding navigation drawer in the app. However it seems that it's not handling the OnItemClick method. When I click on an item nothing happens.How can I make it work?Thanks
//MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer_layout = (DrawerLayout)findViewById(R.id.drawerLayout);
list_view = (ListView)findViewById(R.id.drawerList);
menu_items = getResources().getStringArray(R.array.nav_drawer_items);
list_view.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, menu_items));
list_view.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, menu_items[position] + " was selected", Toast.LENGTH_LONG).show();
}
// MainActivity.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/mainContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView android:id="#+id/drawerList"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:background="#android:color/white"
android:divider="#android:color/black"
android:dividerHeight="1dp"
android:listSelector="#android:color/black"
android:choiceMode="singleChoice"
/>
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:ignore="MergeRootFrame"
tools:context="com.example.MainActivity"
>
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textview1"
android:layout_gravity="center"
android:textStyle="bold"
android:textSize="20sp"
android:gravity="center"
android:layout_marginTop="30dp"/>
<Button
android:id="#+id/Button1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="#drawable/ok_button"
android:layout_marginTop="20dp"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Your DrawerLayout's child Views are incorrectly z-ordered. The View for the drawer - in this case, the ListView - needs to be listed last in order to be on top of everything else.
Do it Simple like this: Add these line of code after setContentView(R.layout.activity_main); or what ever your activity name is.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Initializing Drawer Layout and ActionBarToggle
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){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
Then Move to next step:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId){
try {
switch (itemId) {
case R.id.nav_menu1:
startActivity(new Intent(this, BActivity.class));
break;
case R.id.nav_menu2:
startActivity(new Intent(this, CActivity.class));
break;
}
}
catch (Exception e)
{
e.printStackTrace();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
}
For Left Menu Drawer Complete Simple you can try the following Simple....
MainActivity.class
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] navMenuTitles;
private ArrayList<MainDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for lefdrawer
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(
R.array.dashboard_leftMenu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_dashboard_layout);
mDrawerList = (ListView) findViewById(R.id.main_dash_left_list_drawer);
navDrawerItems = new ArrayList<MainDrawerItem>();
navDrawerItems.add(new MainDrawerItem(navMenuTitles[0], 0,
null, false));
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);
}
private void displayView(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
Toast.makeText(MainActivity.this, ..... + " was selected",Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
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);
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);
}
}
MainDrawerItem.class
public class MainDrawerItem {
private String title;
public MainDrawerItem(){
}
public MainDrawerItem(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
}
For Adapter Class
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<MainDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<MainDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#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);
}
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}
I'm using a navigation drawer in my application with android.support.v4.app.Fragment. The problem is that my navigation menu is always transparent and sometimes when I change the fragment I can see the previous one behind the new one "overlaying" (I said sometimes not always).
This is my main code:
public class Main extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private ImageLoader mLoader;
static String destinationFile;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private boolean isTracking = false;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
Bundle extras;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
String countnotif="";
static int mNotifCount = 0;
Boolean etat=false;
Bitmap btmap;
String myid,fbname;
String value;
CallbackManager callbackManager;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES="My profile info";
public static final String keyid="myaccountid";
public static final String keypwd="myaccountpwd";
public static final String keyhotel="myhotelname";
public static final String keyidhotel="idH";
public static final String keynotifcount="countnotif";
public static final String keynotif="notifmsg";
public static final String keynotifmsg="notificationmsg";
private String myidhotel;
String myaccountname;
TextView myemail;
public static final String keyusername="myusername";
public static final String keymail="mymail";
TextView myname,mymail;
LinearLayout drawerll;
JSONArray thumburl = null;
static String imgfromurl;
String datapass;
ProfileTracker profileTracker;
ImageView myimage;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save the fragment state here
outState.putString("fbuser", myname.getText().toString());
// outState.putString("fbmail",emailT.getText().toString());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.tray);
extras = getIntent().getExtras();
if (extras != null) {
value = extras.getString("hotelname");
}
Toast.makeText(this, "VALUE" + value, Toast.LENGTH_SHORT).show();
mTitle = mDrawerTitle = getTitle();
forceShowActionBarOverflowMenu();
final ActionBar bar = getActionBar();
// bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.blue_pressed_want)));
// getting items of slider from array
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// getting Navigation drawer icons from res
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
drawerll = (LinearLayout) findViewById(R.id.drawerll);
myname=(TextView)findViewById(R.id.usernameacount);
myimage = (ImageView) findViewById(R.id.myimg);
myemail=(TextView)findViewById(R.id.usermailaccount);
// adding nav drawer items to array
// Home
navDrawerItems = new ArrayList<NavDrawerItem>();
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
countnotif = sharedpreferences.getString(keynotifcount, "");
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1), etat, countnotif));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
// Recycle array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting list adapter for Navigation Drawer
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// Enable action bar icon_luncher as toggle Home Button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
MenuInflater inflater = getMenuInflater();
// calling onPrepareOptionsMenu() to show action bars icons
// onCreateOptionsMenu();
invalidateOptionsMenu(); //Setting, Refresh and Rate App
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
displayView(0);
}
Intent intent = getIntent();
if (intent != null)
{
try {
Bundle data = intent.getExtras();
datapass = data.getString("content");
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
public void onActivityResult(int requestCode, int responseCode, Intent data) {
super.onActivityResult(requestCode, responseCode, data);
if(extras!=null) {
callbackManager.onActivityResult(requestCode, responseCode, data);
}
}
/**
* Slider 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 item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();//getSupportMenuInflater();
getMenuInflater().inflate(R.menu.activity_main, menu);
RelativeLayout badgeLayout = (RelativeLayout) menu.findItem(R.id.menu_notif).getActionView();
ImageView bell= (ImageView)badgeLayout.findViewById(R.id.bell);
if (sharedpreferences.contains(keynotifcount)) {
countnotif = sharedpreferences.getString(keynotifcount, "");
mNotifCount= Integer.parseInt(countnotif);
}
if(mNotifCount!=0) {
TextView notifCount = (TextView) badgeLayout.findViewById(R.id.actionbar_notifcation_textview);
notifCount.setVisibility(View.VISIBLE);
notifCount.setText(String.valueOf(mNotifCount));
etat=true;
}
if(mNotifCount==0) {
TextView notifCount = (TextView) badgeLayout.findViewById(R.id.actionbar_notifcation_textviewoff);
etat=false;
}
Toast.makeText(this, "notifcount" + mNotifCount, Toast.LENGTH_SHORT).show();
bell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//startActivity(new Intent(Main.this, Management.class));
displayView(4);
etat=false;
mNotifCount=0;
countnotif= String.valueOf(mNotifCount);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(keynotifcount, countnotif);
editor.commit();
}
});
// return true;
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// title/icon
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.menu_notif:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//called when invalidateOptionsMenu() invoke
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if Navigation drawer is opened, hide the action items
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
boolean drawerOpen = mDrawerLayout.isDrawerOpen(drawerll);
// menu.findItem(R.id.menu_notif).setVisible(drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
private void displayView(int position) {
// update the main content with called Fragment
// new JSONParseimg().execute();
Fragment fragment = new Fragment();
//Fragment fragment = null;
/* android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = new Fragment();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();*/
case 0:
fragment = new Home();
break;
case 1:
fragment = new Profile();
break;
case 2:
fragment = new VraiCateg();
break;
case 3:
fragment = new MyLocation();
break;
case 4:
fragment = new Notification();
break;
case 5:
fragment = new Share();
break;
case 6:
fragment = new About();
break;
case 7:
logout();
Intent in = new Intent(this, Auth.class);
startActivity(in);
finish();
break;
default:
break;
}
if (fragment != null) {
android.support.v4.app.FragmentManager fragmentManager= getSupportFragmentManager();
// Fragment fragment = new Fragment();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(drawerll);
} else {
Log.e("this is mainActivity", "Error in else case");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private void forceShowActionBarOverflowMenu() {
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
this is my first fragment:
public class VraiRela extends Fragment implements StaggeredGridView.OnItemClickListener {
ArrayList<VraiRelations> relationsList;
StaggeredAdapterVraiRelations adapter;
StaggeredGridView staggeredGridView;
String passtitle="";
public static final String inputFormat = "HH:mm:ss";
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.FRANCE);
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES="My profile info";
private String myidhotel;
public static final String keyidhotel="idH";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.vrai_rela_main, container, false);
myidhotel = getArguments().getString("idH");
final String ref_type = getArguments().getString("ref_type");
staggeredGridView = (StaggeredGridView) view.findViewById(R.id.grid_view);
relationsList = new ArrayList<VraiRelations>();
StaggeredAdapterVraiRelations adapter = new StaggeredAdapterVraiRelations(getActivity().getApplicationContext(),R.layout.vrai_rela_list_item_sample,relationsList);
staggeredGridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
staggeredGridView.setOnItemClickListener(this);
return view;
}
#Override
public void onItemClick(StaggeredGridView parent, View view, int position, long id) {
String ref_relation=relationsList.get(position).getRefrelation();
Fragment newFragment = new RelationDetails();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Bundle args=new Bundle();
args.putString("ref_relation",ref_relation);
newFragment.setArguments(args);
Toast.makeText(getActivity().getApplicationContext(), "ref_relation"+ref_relation, Toast.LENGTH_LONG).show();
transaction.remove(VraiRela.this);
transaction.replace(R.id.frame_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}}
this is my layout:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:background="#color/grey"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<LinearLayout
android:id="#+id/drawerll"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/list_item_pressed"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/drawer"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:background="#color/blue_head_want"
android:gravity="center_vertical"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="wrap_content"
android:background="#drawable/profile_head"
android:layout_height="wrap_content">
<ImageView
android:layout_width="135px"
android:layout_height="135px"
android:id="#+id/myimg"
android:src="#drawable/profile" />
</LinearLayout>
<LinearLayout
android:id="#+id/drawer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#color/blue_head_name"
android:id="#+id/usernameacount"
android:textSize="9sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:id="#+id/usermailaccount"
android:textColor="#color/blue_under_head_name"
android:gravity="center"
android:textSize="7sp" />
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/blue_under_head_name" />
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:background="#color/list_background"
android:choiceMode="singleChoice"
android:layout_gravity="start"
android:textColor="#color/blue_item_name"
android:dividerHeight="1dp"
android:alpha="255"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
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 ;)
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.