Je travaille actuellement sur une application Android pour 4.2.2 qui utilise le nouveau NavigationDrawer. Cela fonctionne comme un charme, sauf pour ajouter des icônes.
J'ai trouvé un exemple de code dans lequel la vue Liste devient une disposition relative dans laquelle deux tableaux parallèles sont imbriqués et restitués par un adaptateur de tableau basé sur un modèle de menu, de manière à être synchronisés, je pense.
Voici l'activité principale:
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);
}
}
Voici le modèle de menu:
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);
}
}
Voici l'implémentation ArrayAdapter:
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;
}
}
Le 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>
et la disposition principale:
<!-- 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" />
Comment puis-je simplifier l'approche? Est-il possible d’utiliser un tableau au lieu d’une structure aussi compliquée?.
B.t.w. vous pouvez trouver mon projet sur github sous: https://github.com/greenspand/MediSynced
C'est une application médicale, d'où le nom . Thx y'all.
voici ma mise en page:
<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>
Vous pouvez utiliser une vue de liste personnalisée avec l'adaptateur de liste pour afficher le compteur en plus de l'élément de liste dans le tiroir. Et ajoutez ensuite le code de votre choix à votre méthode de compteur . Voici le code que j'ai implémenté dans mon application de navigation au tiroir de navigation Android:
méthodes getter/setter pour le tiroir:
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;
}
}
C'est l'adaptateur de liste que j'ai utilisé pour afficher la liste. vérifiez la méthode de décompte d'affichage à la fin:
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;
}
}
Disposition de liste correspondante:
<?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>
et voici la classe principale du tiroir N:
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);
}
}
La manière la plus simple que j'ai faite est la suivante:
1. Faites-le comme votre tiroir 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. Ajoutez ces valeurs à votre 'dimens.xml'. Jamais les valeurs hardcode!
<dimen name="spacing_normal">16dp</dimen>
<dimen name="spacing_small">8dp</dimen>
3. Pour le tableau Icons, ajoutez ce tableau de chaînes à '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. Dans votre adaptateur, accédez à ce tableau en utilisant une instance de Typed Array.
TypedArray typedArray=getResources().obtainTypedArray(R.array.array_main_menu);
5. Dans le getView de votre adaptateur, définissez image sur Imageview comme ceci.
mIcon.setImageResource(typedArray.getResourceId(position, -1));
ici, mIcon est votre ImageView.
Avec les versions récentes de Support Library, le moyen le plus simple consiste à utiliser NavigationView. Voici un bon tutoriel , et voici la documentation officielle .
Une NavigationView est incluse comme deuxième vue dans DrawerLayout (au lieu de ListView à partir du code OP), par exemple:
<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" />
Ensuite, le menu devrait être rempli avec des titres et des icônes, comme (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>
Pour plus de détails, veuillez vous référer au premier lien.