Search code examples
androidlistviewonscrolllistener

Change Background color of an item in ListView onscroll?


hello there i have a listview contains many items on it but only 3 items are visible and i want to change the background color of the middle item after scrolling the list

my Activity implements AbsListView.OnScrollListener and i have 2 override methods as shown below

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {

}

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    int firstVisibleRow = AccountList.getFirstVisiblePosition();
    int lastVisibleRow = AccountList.getLastVisiblePosition();
    int middleone = firstVisibleRow+1;

        Account test = (Account) AccountList.getItemAtPosition(middleone);
       // test is the item in the middle of listview 

        Log.i("", "" + middleone + "=" + test.getDescription());
}

I create array list of Account and adapter of Account list Account test is the middle item

and i got it critical as i need now i want to set background color to this row "test"

please any help wish i was clear in my question thanks all


Solution

  • at first thank you all

    finally i found my solution here is it

      @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        wantedView.setBackgroundResource(R.drawable.background_shape);//or color but set background 
    }
    
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    
        int middlePosition = AccountList.getFirstVisiblePosition()+1;
        int firstPosition = AccountList.getFirstVisiblePosition() - AccountList.getHeaderViewsCount();
        int middleChild = middlePosition - firstPosition;
    
        if (middleChild < 0 || middleChild >= AccountList.getChildCount()) {
            Log.w("TAG", " Unable to get view for desired position, because its not being displayed on screen");
            return;
        }
        middleView = AccountList.getChildAt(middleChild);
        middleView.setBackgroundColor(Color.WHITE);
    
    
    
    }
    

    good luck for all :)