How can I change the background color of only the second visible cell in listview ?I only want to change the background color of the second visible cell in the listview. Is there any way to do this. My adapter class:
public class HourAdapter extends BaseAdapter {
private LayoutInflater lInflater;
private String[] hoursValueList;
public HourAdapter(Context context, String[] hoursValueList{
lInflater = LayoutInflater.from(context);
this.hoursValueList = hoursValueList;
}
@Override
public View getView(int position, View convertView,ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.row, parent, false);
}
TextView textHours = view.findViewById(R.id.textRow);
textHours.setText(hoursValueList[position]);
if (position == CustomView.middlePosition) {
view.setBackgroundResource(R.drawable.selected_color);
}
return view;
}
}
and customView class:
public class CustomView extends View {
private String[] hoursList = getResources().getStringArray(R.array.hours);
private ListView listView;
private HourAdapter hourAdapter;
public static int middlePosition;
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, ViewGroup viewGroup) {
super(context);
inflate(context, R.layout.custom_test, viewGroup);
listView = viewGroup.findViewById(R.id.hours_list);
hourAdapter = new HourAdapter(context, hoursList);
listView.setAdapter(hourAdapter);
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
middlePosition = firstVisibleItem+1;
}
}
);
When i scroll down on ListView some other row of ListView also changed background color.
I want only only change the second row of ListView.
I guess you mean that you want to color the second visible item from top and not the second item in the list.
If that is the case, you can simply add an else statement to your getView method of your adapter class to remove the background from the textviews that are not at the second visible item position. Your code would then looks like this:
@Override
public View getView(int position, View convertView,ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.row, parent, false);
}
TextView textHours = view.findViewById(R.id.textRow);
textHours.setText(hoursValueList[position]);
if (position == 1) {
view.setBackgroundResource(R.drawable.selected_color);
}
return view;
}