javaandroidlistviewonitemclicklistener

ListView - get adjacent items of the clicked item


I am trying to make a ListView where you can have no more than 4 items clicked at once. These items have to be adjacent to each other.

When I click my first item, I want to see if the previous OR the following item is clicked already.

Note: When I click an item, I change the background color. So if I want to tell if an item is clicked or not, I just want to check the background color.

public void OnItemClick(AdapterView<?> parent, View, view, int position, long id){

    View currentItem = view;
    currentItem.setBackgroundResource(R.drawable.li_gradient);

    // How do I get the view in front of and behind currentItem
    // to check their current background color? (Assuming they exist)

}

Solution

  • You should do this inside your adapter class, the model item need to have a background resource property.

    Just cast the adapter, get the previous or next item, set the new background and notify the listView

    public void OnItemClick(AdapterView<?> parent, View, view, int position, long id){
    
        YourAdapterClass adapter = (YourAdapterClass) parent.getAdapter();
    
        // TODO check if is a valid position
        YourItem item = (YourItem) adapter.getItem(position-1);
        item.setBackgroundResource(R.drawable.li_gradient);
    
        adapter.notifyDataSetChanged();
    }