如何使 listView 中的一行始终具有相同的颜色 android

How to make a line in the listView always have the same color android

我有 CustomListView:

public class CustomView extends View {

    private String[] hoursList = getResources().getStringArray(R.array.hours); ;
    private String[] minutesList = getResources().getStringArray(R.array.minutes);;
    private ListView listView;
    private HourAdapter hourAdapter;
    private MinuteAdapter minuteAdapter;
 
    public CustomView(Context context) {
        super(context);
    }

    public CustomView(Context context, ViewGroup viewGroup) {
        super(context);
        inflate(context, R.layout.time_picker_test, viewGroup);

        listView = viewGroup.findViewById(R.id.minutes_list);
        minuteAdapter = new MinuteAdapter(context, minutesList);
        listView.setAdapter(minuteAdapter);

        listView = viewGroup.findViewById(R.id.hours_list);
        hourAdapter = new HourAdapter(context, hoursList);
        listView.setAdapter(hourAdapter);

    }
}

和适配器类:

public class MinuteAdapter extends BaseAdapter {
    private LayoutInflater lInflater;
    private String[] minutesValueList;

    public MinuteAdapter(Context context, String[] minutesValueList) {
        lInflater = LayoutInflater.from(context);
        this.minutesValueList = minutesValueList;
    }

    @Override
    public int getCount() {
        return minutesValueList.length;
    }

    @Override
    public Object getItem(int position) {
        return minutesValueList[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @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 textMinutes = view.findViewById(R.id.textRow);
         textMinutes.setText(minutesValueList[position]);

        }

        if (view.getVisibility() == View.VISIBLE) {
            if (position ==2) {
                view.setBackgroundColor(Color.BLUE);
            } else {
                view.setBackgroundColor(Color.WHITE);
            }
        }
        TextView textMinutes = view.findViewById(R.id.textRow);
        textMinutes.setText(minutesValueList[position]);
        return view;
    }
}

我需要,这里(见图片)在中间位置(现在 11,2 和 PM)总是蓝色的(不管这个位置当前有什么元素)。 我用过这个:

if (view.getVisibility() == View.VISIBLE) {
                if (position ==2) {
                    view.setBackgroundColor(Color.BLUE);
                } else {
                    view.setBackgroundColor(Color.WHITE);
                }
            }

但是它改变了元素的颜色。但我需要只有单元格(可见元素的中间)始终是蓝色的。

如果你想要中间行的中间单元格是蓝色的,将 if (position ==2) 更改为 if (position ==1) ,数组中的索引从零开始而不是从 1