I am stucked with my android app. The user interface doesn’t work as I want. I know the reason, but I can’t find the solution:

I have a listview populated with a custom adapter. The background color of each row is white. When the user clicks on one item for the first time, I want to change its background color to green. The app does it, but when that row disappears from screen and comes back, it loses the green color.

When the user clicks for the second time, I want the background of the selected row to change to red, but I have the same issue.

After researching, I know that android is reusing the views in order to increase the performance, but in my case I want to keep those changes.

I read about ViewHolder, notifyDataSetChanged(), view.invalidate, overriding the getItemViewType method, but none of this worked for me. (I guess I'm doing something wrong)

Could you please give me a hand?

Here is my getView method of my class LineAdapter:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
    Station item = getItem(position);
    View v = null;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(layoutResourceId, null);
    } else {
        v = convertView;
    }

    TextView stationName = (TextView) v.findViewById(R.id.stationName);
    stationName.setText(item.getStationName());

    v.setBackgroundColor(Color.WHITE);
    ImageView line_image = (ImageView) v.findViewById(R.id.line);

    line_image.setBackgroundColor(Color.parseColor(setLineColor(line.getLineName())));
    line_image.setImageResource(R.drawable.ic_line_simple);

   return v;
} catch (Exception ex) {
    Log.e(LOG_TAG, "error", ex);
    return null;
}
}

Here is my setOnItemClickListener:

lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener(){

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

            station = (Station)parent.getItemAtPosition(position);
            if (head ==-1) { //first click
                head = position;
                view.setBackgroundColor(Color.GREEN);
            }
            else if (terminal ==-1){  //second click
                terminal = position;
                view.setBackgroundColor(Color.RED); 
         }
         }

Related posts

Recent Viewed