Search code examples
androidandroid-listviewandroid-viewsimpleadapter

SimpleAdapter not keeping position when scrolling


I have a SimpleAdapter which I'm using to display a two line listview. I want the 15th position on this simple adapter to be of a different format but when I scroll the listview around, it looses the position and the formatting changes positions. Is there a solution for this? I've tried mucking around with the convertView but can't seem to get the right format. My code is below. Thanks!

        SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"title", "publisher"}, new int[] {android.R.id.text1, android.R.id.text2}){
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);

            if (position == 15) {
                TextView text1 = (TextView) view.findViewById(android.R.id.text1);
                text1.setTextColor(Color.WHITE);
                TextView text2 = (TextView) view.findViewById(android.R.id.text2);
                text2.setTextColor(Color.WHITE);
                view.setBackgroundColor(getResources().getColor(R.color.teal_dark));
            }

            return view;
        }


    };

Solution

  • Try to add an else clause to reset the format to default format

    if (position == 15) {
        TextView text1 = (TextView) view.findViewById(android.R.id.text1);
        text1.setTextColor(Color.WHITE);
        TextView text2 = (TextView) view.findViewById(android.R.id.text2);
        text2.setTextColor(Color.WHITE);
        view.setBackgroundColor(getResources().getColor(R.color.teal_dark));
    } else {
        TextView text1 = (TextView) view.findViewById(android.R.id.text1);
        text1.setTextColor(Color.BLACK);
        TextView text2 = (TextView) view.findViewById(android.R.id.text2);
        text2.setTextColor(Color.BLACK);
        view.setBackgroundColor(getResources().getColor(R.color.teal_light));
    }