如何为导航栏中的每个列表项设置背景图像。

时间:2013-09-05 11:43:44

标签: android android-listview

我正在尝试用不同的图像替换android导航抽屉中的每个列表项。任何人都可以详细说明如何实现这一目标吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

首先你可以像这样创建一个数组

final String[] NAV_OPTIONS =  new String[]{"menuOne","menuTwo","menuThree","menuFour"};

然后当我们将listview传递给适配器时,我们就像这样

leftDraw.setAdapter(new menuAdapter(Nav_OPTIONS));

适配器看起来应该是这样的

    public class menuAdapter extends BaseAdapter {

        String[] menu;

        public menuAdapter(String[] data) {

            menu = data;

        }

        @Override
        public View getView(final int position, View convertView,
                ViewGroup parent) {


            LayoutInflater li = getLayoutInflater();

            //here we just check the position and depending on the string inflate one of our layout xmls
            if(menu[position].equals("menuOne")){
               //inflate our first layout
               convertView = li.inflate(R.layout.menu_one, null);

            }
            else if(menu[position].equals("menuTwo")){
                //inflate our second layout
            convertView = li.inflate(R.layout.menu_two, null);
           }
           else if(menu[position].equals("menuThree")){
                //inflate our third
                convertView = li.inflate(R.layout.menu_three. null);
           }
           else if(menu[position].equals("MenuFour")){
               //and finally our fourth
               convertView = li.inflate(R.layout.menu_four, null);

               //within these if statements we can inflate any buttons, switches, imageviews  
               //we just need to reference them from within the statement as we're infalting the xml in which they are contained
               Button example = (button). convertView.findViewById(R.id.example_button);

           }

           //return the view 
           return covertView;
}

你基本上只需要创建单独的XML并根据数组中的位置对它们进行充气。

修改

我刚刚意识到你可能只想要添加一个单独的图像而不是整个布局。在这种情况下,我的解决方案可能比你需要的多一点。

不同的图像以类似的方式工作。只需将您的图像存储在一个数组中,然后根据适配器的索引(int位置)检索它们。