【问题标题】:How to add image to navigation drawer/ listeview?如何将图像添加到导航抽屉/列表视图?
【发布时间】:2016-02-25 06:45:23
【问题描述】:

Android 新手,我有一个运行良好的导航抽屉。但现在我想为每个选项插入图像 - 比如“家庭”的 1 个图像和“扫描条形码”的另一个图像等。

我为此做了一些教程搜索,但找不到合适的解决方案。有什么建议?提前致谢。

NavigationDrawerFrag.xml

/**
 * .
 *
 */package com.androidatc.customviewindrawer;

//import android.support.v4.app.FragmentManager;
import android.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
//import android.support.v4.app.Fragment;
import android.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

/**
 * Fragment used for managing interactions for and presentation of a navigation drawer.
 * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
 * design guidelines</a> for a complete explanation of the behaviors implemented here.
 */
public class NavigationDrawerFragment extends Fragment {

    /**
     * Remember the position of the selected item.
     */
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    /**
     * Per the design guidelines, you should show the drawer on launch until the user manually
     * expands it. This shared preference tracks this.
     */
    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

    /**
     * A pointer to the current callbacks instance (the Activity).
     */
    private NavigationDrawerCallbacks mCallbacks;

    /**
     * Helper component that ties the action bar to the navigation drawer.
     */
    private ActionBarDrawerToggle mDrawerToggle;

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerListView;
    private View mFragmentContainerView;

    private int mCurrentSelectedPosition = 0;
    private boolean mFromSavedInstanceState;
    private boolean mUserLearnedDrawer;

    public NavigationDrawerFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Read in the flag indicating whether or not the user has demonstrated awareness of the
        // drawer. See PREF_USER_LEARNED_DRAWER for details.
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

        if (savedInstanceState != null) {
            mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
            mFromSavedInstanceState = true;
        }


        // Select either the default item (0) or the last selected item.
        selectItem(mCurrentSelectedPosition);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Indicate that this fragment would like to influence the set of actions in the action bar.
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mDrawerListView = (ListView) inflater.inflate(
                R.layout.fragment_navigation_drawer, container, false);
        mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectItem(position);
                loadFragmentLayout(position);
            }
        });
        mDrawerListView.setAdapter(new ArrayAdapter<String>(
                getActionBar().getThemedContext(),
                android.R.layout.simple_list_item_activated_1,
                android.R.id.text1,
                new String[]{
                        getString(R.string.title_section1),
                        getString(R.string.title_section2),
                        getString(R.string.title_section3),
                        getString(R.string.title_section4),
                        getString(R.string.title_section5),
                }));
        mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
        return mDrawerListView;
    }

    /**
     * Diplaying fragment view for selected nav drawer list item
     */
    private void loadFragmentLayout(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;
        switch (position) {
            case 0:
                fragment = new MainViewFragment();
                break;
            case 1:
                fragment = new BarCodeScanFrag();
                break;
            case 2:
                fragment = new SearchBookFrag();
                break;
            case 3:
                fragment = new MyAccFrag();
                break;
            case 4:
//                fragment = new BorrowFrag();
                break;
            default:
                break;
        }
        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.container, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerListView.setItemChecked(position, true);
            mDrawerListView.setSelection(position);
            mDrawerLayout.closeDrawer(Gravity.LEFT);
        } else {
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    /**
     * Users of this fragment must call this method to set up the navigation drawer interactions.
     *
     * @param fragmentId   The android:id of this fragment in its activity's layout.
     * @param drawerLayout The DrawerLayout containing this fragment's UI.
     */
    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        mDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),                    /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (!isAdded()) {
                    return;
                }

               // getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }

                if (!mUserLearnedDrawer) {
                    // The user manually opened the drawer; store this flag to prevent auto-showing
                    // the navigation drawer automatically in the future.
                    mUserLearnedDrawer = true;
                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(getActivity());
                    sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
                }

                //getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        };

        // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
    // per the navigation drawer design guidelines.
    if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
        mDrawerLayout.openDrawer(mFragmentContainerView);
    }

    // Defer code dependent on restoration of previous instance state.
    mDrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mDrawerToggle.syncState();
        }
    });

    mDrawerLayout.setDrawerListener(mDrawerToggle);
}

    private void selectItem(int position) {
        mCurrentSelectedPosition = position;
        if (mDrawerListView != null) {
            mDrawerListView.setItemChecked(position, true);
        }
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        if (mCallbacks != null) {
            mCallbacks.onNavigationDrawerItemSelected(position);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallbacks = (NavigationDrawerCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Forward the new configuration the drawer toggle component.
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // If the drawer is open, show the global app actions in the action bar. See also
        // showGlobalContextActionBar, which controls the top-left area of the action bar.
        if (mDrawerLayout != null && isDrawerOpen()) {
            inflater.inflate(R.menu.global, menu);
            showGlobalContextActionBar();
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // it is for navigation menu
        Fragment fragment = null;
        if (mDrawerToggle.onOptionsItemSelected(item)) {
//            Toast.makeText(getActivity(), "Inside Toggle", Toast.LENGTH_SHORT).show();

            return true;
        }

        // below is not called for login. why?
//        Toast.makeText(getActivity(), item.getItemId() + "=" + R.id.action_login + "B4 Action Login.", Toast.LENGTH_SHORT).show();


//        if (item.getItemId() == R.id.action_logout) {
////            Toast.makeText(getActivity(), "Action Login.", Toast.LENGTH_SHORT).show();
//            fragment = new LoginFrag();
//
//            if (fragment != null) {
//                FragmentManager fragmentManager = getFragmentManager();
//                fragmentManager.beginTransaction()
//                        .replace(R.id.container, fragment).commit();
//
//
//            }
//
//            return true;
//        }
//        else {
//            Toast.makeText(getActivity(), "Home .", Toast.LENGTH_SHORT).show();
//            fragment = new HomeFrag();

            if (fragment != null) {
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction()
                        .replace(R.id.container, fragment).commit();


            }

            return true;
        }

//        return super.onOptionsItemSelected(item);
//    }

    /**
     * Per the navigation drawer design guidelines, updates the action bar to show the global app
     * 'context', rather than just what's in the current screen.
     */
    private void showGlobalContextActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setTitle(R.string.app_name);
    }

    private ActionBar getActionBar() {
        return ((ActionBarActivity) getActivity()).getSupportActionBar();
    }

    /**
     * Callbacks interface that all activities using this fragment must implement.
     */
    public static interface NavigationDrawerCallbacks {
        /**
         * Called when an item in the navigation drawer is selected.
         */
        void onNavigationDrawerItemSelected(int position);
    }
}

Fragment_navigation_drawer.xml

<ListView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#cccc"
    tools:context=".NavigationDrawerFragment" />

【问题讨论】:

  • 哦!但是为什么你使用自定义导航抽屉
  • 我从某个地方得到了代码,所以在上面构建我的应用程序。
  • 如果您使用的是Android studio 1.5.1及以上版本,studio本身会在项目创建开始时提供类和相应的xml来绘制导航抽屉。
  • 我使用的是 Android Studio 1.4

标签: android navigation-drawer


【解决方案1】:

您必须为这种情况制作自定义适配器。

public class NavDrawerListAdapter extends BaseAdapter {

private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;

public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
    this.context = context;
    this.navDrawerItems = navDrawerItems;
}

@Override
public int getCount() {
    return navDrawerItems.size();
}

@Override
public Object getItem(int position) {       
    return navDrawerItems.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater mInflater = (LayoutInflater)
                context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.drawer_list_item, null);
    }

    ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
    TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
    TextView txtCount = (TextView) convertView.findViewById(R.id.counter);

    imgIcon.setImageResource(navDrawerItems.get(position).getIcon());        
    txtTitle.setText(navDrawerItems.get(position).getTitle());

    // displaying count
    // check whether it set visible or not
    if(navDrawerItems.get(position).getCounterVisibility()){
        txtCount.setText(navDrawerItems.get(position).getCount());
    }else{
        // hide the counter view
        txtCount.setVisibility(View.GONE);
    }

    return convertView;
}

}

如需完整参考,您可以访问以下链接: http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/

【讨论】:

    【解决方案2】:

    在这里你为你的 ListView 设置数据,它不包含图像

    mDrawerListView.setAdapter(new ArrayAdapter<String>(
                        getActionBar().getThemedContext(),
                        android.R.layout.simple_list_item_activated_1,
                        android.R.id.text1,
                        new String[]{
                                getString(R.string.title_section1),
                                getString(R.string.title_section2),
                                getString(R.string.title_section3),
                                getString(R.string.title_section4),
                                getString(R.string.title_section5),
                        }));
    

    如果您想将图像添加到您的 ListView,您需要创建一个自定义适配器,其中包含您的 ListView 的图像
    试试Custom Listview with Image and Text using ArrayAdapter

    【讨论】:

      【解决方案3】:

      将此添加到您的主要活动中:

           <?xml version="1.0" encoding="utf-8"?>
          <android.support.v4.widget.DrawerLayout
              android:id="@+id/drawer_layout"
              xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              xmlns:tools="http://schemas.android.com/tools"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:fitsSystemWindows="true"
              tools:openDrawer="start">
      
              <!-- REST OF YOUR CONTENT-->
      
      
          <android.support.design.widget.NavigationView
              android:id="@+id/nav_view"
              android:layout_width="wrap_content"
              android:layout_height="match_parent"
              android:layout_gravity="start"
              android:fitsSystemWindows="true"
              app:menu="@menu/drawer_menu"/>
      
      </android.support.v4.widget.DrawerLayout>
      

      抽屉布局应该是你的根元素:

      在 menu.xml 文件夹中添加新菜单:

          <?xml version="1.0" encoding="utf-8"?>
      <menu xmlns:android="http://schemas.android.com/apk/res/android">
      
          <group android:id="@+id/menu" android:checkableBehavior="single">
              <item
                  android:id="@+id/nav_home"
                  android:icon="@null"
                  android:title="Home" />
      
              <item
                  android:id="@+id/nav_settings"
                  android:icon="@null"
                  android:title="Settings" />
      
              <item
                  android:id="@+id/nav_playlists"
                  android:icon="@null"
                  android:title="PlayLists" />
          </group>
      </menu>
      

      将此添加到您的主要活动onCreate 方法中:

      final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
          final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                  this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
          };
      
          drawer.setDrawerListener(toggle);
          toggle.syncState();
      
      
          NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
          navigationView.setNavigationItemSelectedListener(this);
      

      这样做:

         public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
      
      ... Your Code....
      
          public boolean onNavigationItemSelected(MenuItem item) {
              int id = item.getItemId();
              switch (id) {
                  case R.id.nav_settings:
                      Intent settingsIntent = new Intent(this, SettingsActivity.class);
                      startActivity(settingsIntent);
                      break;
                  case R.id.nav_playlists:
                      Intent playlistsIntent = new Intent(this,PlayList.class);
                      startActivity(playlistsIntent);
                      break;
              }
              return false;
          }
      

      以上代码表示实现导航项点击监听并覆盖该方法。就是这样!

      【讨论】:

      • 如果他/她加上这段代码,问题就解决了
      • 侯赛因,我用上面试过了,它无法识别 AppCompatActivity 和 NavigationView。
      • 将您的 android studio 更新到 1.5.1 或更高版本
      【解决方案4】:

      您可以查看我实现此Github Link 的github 链接,或者您也可以按照slidenerd 教程系列Android RecyclerView Example Part 1: Android Material Design Tutorials 在其中实现您想要实现的目标

      【讨论】:

      • 请不要只链接到外部资源。他们可能有一天会不复存在。即使链接已损坏,您的回答也应该有效。
      • @Naresh:您的 github 和教程链接都非常有帮助。谢谢..:)
      【解决方案5】:

      在这里我分享一些简单的编辑,通过你可以轻松实现。

      只需编辑 nav_header_main.xml

      <Button
          android:id="@+id/btn_home"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_marginLeft="10dp"
          android:layout_marginTop="3dp"
          android:background="@null"
          android:drawablePadding="6dp"
          android:drawableRight="@mipmap/grocery_logo"
          android:gravity="left|center"
          android:padding="6dp"
          android:text="Home"
          android:textColor="@color/colorPrimary" />
      <TextView
          android:layout_width="match_parent"
          android:layout_height="1dp"
      
          android:background="@color/border" />
      
      
      <LinearLayout
          android:id="@+id/nav_quicklist_layout"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="horizontal"
          android:weightSum="1">
      
          <ImageView
              android:layout_width="50dp"
              android:layout_height="51dp"
              android:layout_weight="0.05"
              android:src="@mipmap/quicklist_menu" />
      
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_gravity="center"
              android:layout_marginLeft="10dp"
              android:text="Quick List"
              android:textAlignment="center"
              android:textColor="@color/menu_text_color"
              android:textSize="13sp" />
      
      </LinearLayout>
      
      <TextView
          android:layout_width="match_parent"
          android:layout_height="1dp"
          android:background="@color/border" />
      
      
      <LinearLayout
          android:id="@+id/nav_myaccount_layout"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:orientation="horizontal"
          android:weightSum="1">
      
          <ImageView
              android:layout_width="50dp"
              android:layout_height="51dp"
              android:layout_weight="0.05"
              android:src="@mipmap/my_account" />
      
          <TextView
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_gravity="center"
              android:layout_marginLeft="10dp"
              android:text="My Account"
              android:textAlignment="center"
              android:textColor="@color/menu_text_color"
              android:textSize="13sp" />
      
      </LinearLayout>
      
      <TextView
          android:layout_width="match_parent"
          android:layout_height="1dp"
          android:background="@color/border" />
      

      并在 MainActivity.java 类中使用它来获取设计。

           NavigationView navigationView = (NavigationView)       findViewById(R.id.nav_view);
          navigationView.setNavigationItemSelectedListener(this);
          for (int i = 0; i < navigationView.getMenu().size(); i++) {
              MenuItem item = navigationView.getMenu().getItem(i);
              if (i != 2) {
                  Drawable dr = item.getIcon();
                  System.out.println(i + "-----drawable..." + dr);
      
                  Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
      
                  Drawable d = new BitmapDrawable(getResources(),  Bitmap.createBitmap(bitmap, 0, 0, 72, 72));
                  navigationView.getMenu().getItem(i).setIcon(d);
              }
      
      
          LinearLayout lay = (LinearLayout) navigationView.getHeaderView(0);
          Button btn_home = (Button) lay.findViewById(R.id.btn_home);
          btn_home.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
      
                  fragment = new Home();
                  if (fragment != null) {
                      title_tv.setText("Grocery");
                      FragmentTransaction ft =  getSupportFragmentManager().beginTransaction();
                      ft.replace(R.id.content_frame, fragment);
                      ft.commit();
                  }
                  DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                  drawer.closeDrawer(GravityCompat.START);
              }
          });
          LinearLayout nav1 = (LinearLayout) lay.findViewById(R.id.nav_quicklist_layout);
          nav1.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
      
                  fragment = new CreateQuickList();
                  if (fragment != null) {
                      title_tv.setText("SRSGrocery");
                      FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                      ft.replace(R.id.content_frame, fragment);
                      ft.commit();
                  }
                  DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                  drawer.closeDrawer(GravityCompat.START);
              }
          });
      
          LinearLayout nav2 = (LinearLayout) lay.findViewById(R.id.nav_myaccount_layout);
          nav2.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
      
                  fragment = new MyAccount();
                  if (fragment != null) {
                      title_tv.setText("SRSGrocery");
                      FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                      ft.replace(R.id.content_frame, fragment);
                      ft.commit();
                  }
                  DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
                  drawer.closeDrawer(GravityCompat.START);
              }
          });
      

      【讨论】:

        【解决方案6】:

        这是你必须在抽屉列表视图上设置的基本适配器类

        public class NavDrawerListAdapter extends BaseAdapter {
        
        private Context context;
        private ArrayList<NavDrawerItem> navDrawerItems;
        
        public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
            this.context = context;
            this.navDrawerItems = navDrawerItems;
        }
        
        @Override
        public int getCount() {
            return navDrawerItems.size();
        }
        
        @Override
        public Object getItem(int position) {       
            return navDrawerItems.get(position);
        }
        
        @Override
        public long getItemId(int position) {
            return position;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater mInflater = (LayoutInflater)
                        context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
                convertView = mInflater.inflate(R.layout.drawer_list_item, null);
            }
        
            ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
            TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
            TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
        
            imgIcon.setImageResource(navDrawerItems.get(position).getIcon());        
            txtTitle.setText(navDrawerItems.get(position).getTitle());
        
            // displaying count
            // check whether it set visible or not
            if(navDrawerItems.get(position).getCounterVisibility()){
                txtCount.setText(navDrawerItems.get(position).getCount());
            }else{
                // hide the counter view
                txtCount.setVisibility(View.GONE);
            }
        
            return convertView;
        }
        

        here查找完整代码

        【讨论】:

          【解决方案7】:

          当您将图像放入导航抽屉时,您必须声明一个布局,在本例中为 relativeLayout。 在布局xml中声明一个布局,现在将图像放入布局中,然后放入listView。

          <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/drawer_layout"
              android:layout_width="match_parent"
              android:layout_height="match_parent" >
          
              <!-- main content -->
          
              <FrameLayout
                  android:id="@+id/content_frame"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent" >
              </FrameLayout>
          
              <!-- Menu -->
          
              <RelativeLayout
                  android:id="@+id/left_drawer"
                  android:layout_width="240dp"
                  android:layout_height="match_parent"
                  android:layout_gravity="start"
                  android:background="@drawable/degradee"
                  android:orientation="vertical" >
          
                  <ImageView
                      android:id="@+id/image_view"
                      android:layout_width="match_parent"
                      android:layout_height="200dp"
                      android:background="@drawable/theworldisyours" />
          
                  <ListView
                      android:id="@+id/list_view_drawer"
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:layout_below="@id/image_view"
                      android:choiceMode="singleChoice" />
              </RelativeLayout>
          
          </android.support.v4.widget.DrawerLayout>
          

          现在在你的活动中

          public class MainActivity extends ActionBarActivity {
          
              private String[] mOptionMenu;
              private DrawerLayout mDrawerLayout;
              private RelativeLayout mDrawerRelativeLayout;
              private ListView mDrawerList;
              private ActionBarDrawerToggle mDrawerToggle;
          
              private CharSequence mTitleSection;
              private CharSequence mTitleApp;
              private Fragment mFragment = null;
          
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_main);
          
                  mOptionMenu = new String[] { getString(R.string.first_fragment),
                          getString(R.string.second_fragment),
                          getString(R.string.third_fragment) };
                  mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
                  mDrawerRelativeLayout = (RelativeLayout) findViewById(R.id.left_drawer);
                  mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
                  mDrawerList.setAdapter(new ArrayAdapter<String>(getSupportActionBar()
                          .getThemedContext(), android.R.layout.simple_list_item_1,
                          mOptionMenu));
                  initContentWithFirstFragment();
          
                  mDrawerList.setOnItemClickListener(new OnItemClickListener() {
                      @Override
                      public void onItemClick(AdapterView<?> parent, View view,
                              int position, long id) {
          
                          switch (position) {
                          case 0:
                              mFragment = new FirstFragment();
                              break;
                          case 1:
                              mFragment = new SecondFragment();
                              break;
                          case 2:
                              mFragment = new ThirdFragment();
                              break;
                          }
          
                          FragmentManager fragmentManager = getSupportFragmentManager();
          
                          fragmentManager.beginTransaction()
                                  .replace(R.id.content_frame, mFragment).commit();
          
                          mDrawerList.setItemChecked(position, true);
          
                          mTitleSection = mOptionMenu[position];
                          getSupportActionBar().setTitle(mTitleSection);
          
                          mDrawerLayout.closeDrawer(mDrawerRelativeLayout);
                      }
                  });
                  mDrawerList.setItemChecked(0, true);
                  mTitleSection = getString(R.string.first_fragment);
                  mTitleApp = getTitle();
          
                  mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                          R.drawable.ic_drawer, R.string.drawer_open,
                          R.string.drawer_close) {
          
                      public void onDrawerClosed(View view) {
                          getSupportActionBar().setTitle(mTitleSection);
                          ActivityCompat.invalidateOptionsMenu(MainActivity.this);
                      }
          
                      public void onDrawerOpened(View drawerView) {
                          getSupportActionBar().setTitle(R.string.app_name);
                          ActivityCompat.invalidateOptionsMenu(MainActivity.this);
                      }
                  };
          
                  mDrawerLayout.setDrawerListener(mDrawerToggle);
          
                  getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                  getSupportActionBar().setHomeButtonEnabled(true);
              }
          
              @Override
              public boolean onCreateOptionsMenu(Menu menu) {
          
                  getMenuInflater().inflate(R.menu.main, menu);
                  return true;
              }
          
              @Override
              public boolean onOptionsItemSelected(MenuItem item) {
          
                  if (mDrawerToggle.onOptionsItemSelected(item)) {
                      return true;
                  }
          
                  switch (item.getItemId()) {
                  case R.id.action_settings:
                      Toast.makeText(this, R.string.action_settings, Toast.LENGTH_SHORT)
                              .show();
                      ;
                      break;
                  default:
                      return super.onOptionsItemSelected(item);
                  }
          
                  return true;
              }
          
              @Override
              protected void onPostCreate(Bundle savedInstanceState) {
                  super.onPostCreate(savedInstanceState);
                  mDrawerToggle.syncState();
              }
          
              @Override
              public void onConfigurationChanged(Configuration newConfig) {
                  super.onConfigurationChanged(newConfig);
                  mDrawerToggle.onConfigurationChanged(newConfig);
              }
          
              public void initContentWithFirstFragment(){
          
                  mTitleSection =getString(R.string.first_fragment);
                  getSupportActionBar().setTitle(mTitleSection);
                  mFragment = new FirstFragment();
                  FragmentManager fragmentManager = getSupportFragmentManager();
          
                  fragmentManager.beginTransaction()
                          .replace(R.id.content_frame, mFragment).commit();
              }
          }
          

          您可以查看this post 和这个example in GitHub

          【讨论】:

            【解决方案8】:

            创建一个单独的 xml 布局,并将该布局作为 Header 添加到您的 listView。

            尝试以下步骤来学习它。

            如果您使用的是 Android Studio,

            1. 开始一个新的示例项目。
            2. 为您的项目命名。点击下一步。选择
            3. 最低 SDK。点击下一步。
            4. 系统会提示您“向移动设备添加活动”。
            5. 选择“导航抽屉活动”,然后单击下一步。
            6. 创建项目。

              检查项目。你会有一个想法。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多