2013-12-12 54 views
1

我剛剛在我的Android應用程序中創建了一個抽屜,現在我想在每個菜單項旁邊包含圖標。爲此,我創建了一個list_item_drawer.xml文件,它看起來像這樣:如何讓我的Android圖像抽屜中的圖標?

<?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

您是否有實現自己的ArrayAdapter自定義getView方法? – JJ86

回答

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

+0

就像給未來讀者的提示。我從第一個鏈接獲取了第一個代碼,並在最上面添加了一個'final Integer []圖標= {R.drawable.side_menu_icon_dummy,R.drawable.side_menu_icon_dummy2};'。這就像一個魅力。謝謝! – kramer65

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); 
    } 
} 
相關問題