Change background colour of current listview item in adapter getView method

前端 未结 7 1176
迷失自我
迷失自我 2020-12-03 19:20

I am building a custom adapter for a listview - I would like this adapter to give the listview alternating background colours.

boolean alternate = false;

@         


        
相关标签:
7条回答
  • 2020-12-03 20:03

    I wanted to highlight the solution so people aren't confused.

    If you want the colors/image, or whatever alteration done on the listview at draw time you need to set it in the getView like below, but if you want it to show on click you need to do it in an onClick method like below.

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            if(view == null) {
                view = inflater.inflate(R.layout.dashboard_item, parent, false);
            }
    
            if(selected[position]) {
                view.setBackgroundColor(Color.LTGRAY);
            } else {
                selected[position] = false;
                view.setBackgroundColor(Color.WHITE);
            }
            return view;
        }
    
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //this is just my custom object..you could also assign your boolean here to see if it is "highlighted"
                Item o = (Item)listView.getItemAtPosition(position);
                if(adapter.selected[position] == true) {
                    adapter.selected[position] = false;
                    view.setBackgroundColor(Color.WHITE);
                } else {
                    adapter.selected[position] = true;
                    view.setBackgroundColor(Color.LTGRAY);
                }
         }
    

    My boolean check is just a boolean array like

    private boolean[] selected;
    

    I initalize it in the my subclass of the ArrayAdapater constructor.

    selected = new boolean[objects.size()];
    Arrays.fill(selected, Boolean.FALSE);
    
    0 讨论(0)
提交回复
热议问题