Home > Software engineering >  Android Studio: Unable to change background color and text color based on boolean
Android Studio: Unable to change background color and text color based on boolean

Time:06-02

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;
        }
    }

CodePudding user response:

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

CodePudding user response:

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.

  • Related