skip to Main Content

I am building a todo application. My goal is for the item’s background color to change to red and the font to white, if urgent = true (boolean).

I am able to do this, but unfortunately once it changes the true todo, it will also change the todo before, even if it equals false.

I know the issue is in the getView method (see below). I have tried moving the textView = newView.findViewById(R.id.textView), above the if old == null statement, but that seems to crash the app. I have also moved the if urgent == true statement into the other if statement, and that won’t work either.

Any ideas what may be causing the issue?

        @Override
        public View getView(int position, View old, ViewGroup parent) {

            View newView = old;
            LayoutInflater inflater = getLayoutInflater();

            if(old == null) {
                newView = inflater.inflate(R.layout.todo_items, parent, false);
            }

            textView = newView.findViewById(R.id.textView);
            textView.setText(getItem(position).toString());

            if(urgent == true) {
                newView.setBackgroundColor(Color.RED);
                textView.setTextColor(Color.WHITE);
            }

            return newView;
        }
    }

2

Answers


  1. I think you need to have an array (or list) of urgent variables, for each position in the list. When item in the list is updated by scroll of by other reason, all views are updated according to the one urgent var.

    Login or Signup to reply.
  2. You need an array of booleans to keep track of the state for each item in the listview

    Try changing

    if(urgent == true) {
       newView.setBackgroundColor(Color.RED);
       textView.setTextColor(Color.WHITE);
    }
    

    To

    if(urgent[position]) {
        newView.setBackgroundColor(Color.RED);
        textView.setTextColor(Color.WHITE);
    } else {
        //Put here the default colors
        newView.setBackgroundColor(  );
        textView.setTextColor(  );
    }
    

    this should fix the issue, also you don’t need to do if(boolean == true) if(boolean) is enough

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search