Custom adapter for navigation drawer

后端 未结 2 753
别那么骄傲
别那么骄傲 2020-12-18 10:20

I have a working navigation drawer that uses ArrayAdapter as shown in the documentation. I want to set ImageView icons for each of the navigation d

2条回答
  •  悲哀的现实
    2020-12-18 11:03

    For your custom adapter:

    public class NavDrawerAdapter extends ArrayAdapter
    {
        private final Context context;
        private final int layoutResourceId;
        private NavDrawerItem data[] = null;
    
        public NavDrawerAdapter(Context context, int layoutResourceId, NavDrawerItem [] data)
        {
            super(context, layoutResourceId, data);
            this.context = context;
            this.layoutResourceId = layoutResourceId;
            this.data = data;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    
            View v = inflater.inflate(layoutResourceId, parent, false);
    
            ImageView imageView = (ImageView) v.findViewById(R.id.navDrawerImageView);
            TextView textView = (TextView) v.findViewById(R.id.navDrawerTextView);
    
            NavDrawerItem choice = data[position];
    
            imageView.setImageResource(choice.icon);
            textView.setText(choice.name);
    
            return v;
        }
    }
    

    For NavDrawerItem:

    public class NavDrawerItem
    {
        public int icon;
        public String name;
    
        public NavDrawerItem(int icon, String name)
        {
            this.icon = icon;
            this.name = name;
        }
    }
    

    For drawer_list_item.xml:

    
    
        
    
        
    
    
    

    In MainActivity.java, instantiate an array of NavDrawerItem objects, with the appropriate drawable and name for each, and then pass this array when you set the adapter, like so:

    mDrawerList.setAdapter(new YourAdapter(this, R.layout.drawer_list_item, yourArray));

提交回复
热议问题