私は現在、新しいNavigationDrawerを使用するAndroid 4.2.2用のアプリに取り組んでいます。アイコンを追加する以外は、チャームのように機能します。
リストビューが相対レイアウトになり、メニューモデルに基づいて2つの並列配列がネストされ、配列アダプターによってレンダリングされるサンプルコードがいくつか見つかりました。
これが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);
}
}
ここにメニューモデルがあります:
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);
}
}
次に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;
}
}
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>
そしてメインレイアウト:
<!-- 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" />
どうすればアプローチを簡略化できますか。このような複雑な構造の代わりに1つの配列を使用する方法はありますか?.
B.t.w.あなたは私のプロジェクトをgithubの以下で見つけることができます: https://github.com/greenspand/MediSynced
それは医療アプリなので、その名前です。ありがとうございます。
これが私のレイアウトです:
<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>
カスタムリストビューとリストアダプターを使用して、ドロワーのリストアイテムのほかにカウンターを表示できます。次に、カウンターメソッドに必要なコードを追加します。サポートされているナビゲーションドロワーに実装したコードは次のとおりですAndroid app:
引き出しのゲッター/セッターメソッドクラス:
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;
}
}
これは、リストを表示するために使用したリストアダプターです。最後に表示カウント方法を確認してください:
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;
}
}
対応するリストのレイアウト:
<?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>
そして、これがメインのN-drawerクラスです:
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);
}
}
私がやった最も簡単な方法はこの方法です:
1。これをあなたの引き出しの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。これらの値を「dimens.xml」に追加します。値をハードコードしないでください!
<dimen name="spacing_normal">16dp</dimen>
<dimen name="spacing_small">8dp</dimen>
3。アイコン配列の場合、この文字列配列を '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。アダプターで、型付き配列インスタンスを使用してこの配列にアクセスします。
TypedArray typedArray=getResources().obtainTypedArray(R.array.array_main_menu);
5。アダプターのgetView内で、イメージを次のようにImageviewに設定します。
mIcon.setImageResource(typedArray.getResourceId(position, -1));
ここでmIconはImageViewです。
Support Libraryの最近のバージョンでは、NavigationViewを使用するのが最も簡単な方法です。 ここに素敵なチュートリアルがあります 、そして ここに公式ドキュメントがあります 。
NavigationViewは、(OPコードからのListViewではなく)DrawerLayoutの2番目のビューとして含まれています。次に例を示します。
<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" />
次に、メニューに(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>
詳細については、最初のリンクを参照してください。