我刚在Android应用中创建了一个抽屉,现在我想在每个菜单项旁边添加图标。为此,我创建了一个list_item_drawer.xml文件,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_drawer_menu_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="23dp"
android:text="Menu item"
/>
<ImageView
android:id="@+id/image_drawermenu_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/placeholder"/>
</LinearLayout>
然后我在我的MainActivity中调用此文件,如下所示:
final String[] menuEntries = {"Overview","New Payment"};
final String[] fragments = {
"com.mycompany.fragment.OverviewFragment",
"com.mycompany.fragment.DetailsFragment",
};
private ActionBarDrawerToggle drawerToggle;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_root);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item_drawer, R.id.text_drawer_menu_item, menuEntries);
etc..
奇怪的是,即使每个菜单项现在都具有该占位符图像文件的高度,我也看不到显示的图像文件。所以我的第一个问题是:如何显示图像文件?
但即使显示该图像文件,我也不知道(问题二),如何为每个菜单项设置一个独特的图标?
欢迎所有提示!
答案 0 :(得分:2)
默认情况下,ArrayAdapter在提供的视图中查找textview并仅更新文本。要更新视图中的图像,您需要扩展ArrayAdapter并使用以下内容覆盖getView():
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
textView.setText(values[position]);
// Change the icon for Windows and iPhone
String s = values[position];
if (s.startsWith("Windows7") || s.startsWith("iPhone")
|| s.startsWith("Solaris")) {
imageView.setImageResource(R.drawable.no);
} else {
imageView.setImageResource(R.drawable.ok);
}
return rowView;
}
源: http://www.vogella.com/articles/AndroidListView/article.html#tutorial_ownadapter
http://developer.android.com/reference/android/widget/ArrayAdapter.html
答案 1 :(得分:0)
您可以使用自定义列表视图和列表适配器来显示抽屉中列表项之外的图标。然后将您想要的任何代码添加到主抽屉类中。 这是我在导航抽屉支持的Android应用程序中实现的代码,它包含图标,标题,标签和计数器:
抽屉的getter / setter方法类:
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抽屉类:
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);
}
}