Save textView color in listView with sharedPreferences

Viewed 95

I have listView and a custom adapter in fragment, which contains only a textView called list_content. I want the user to change the color of the textView onClick. So far this is my relevant code onCreate along with listView setOnItemClickedListener:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //Inflate
    View view = inflater.inflate(R.layout.fragment_grocery_list, container, false);

    //Load text color
    color = getContext().getSharedPreferences("com.android.me", MODE_PRIVATE);
    colourValue = color.getString("colourValue", null);

    //list view
    listView = (ListView) view.findViewById(R.id.groceryListView);


    //arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, groceries);
    arrayAdapter = new customAdapter(getContext(), groceries);
    listView.setAdapter(arrayAdapter);

    //list view click listener
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

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

            list_content = (TextView) view.findViewById(R.id.list_content);

            color = getContext().getSharedPreferences("com.android.me", MODE_PRIVATE);
            colourValue = color.getString("colourValue", null);

            if (list_content.getCurrentTextColor() == Color.parseColor("#000000")){ //Check if item is checked or not | if (list_content.getCurrentTextColor() == Color.parseColor("#000000")) {

                color.edit().putString("colourValue","#a7a7a7").apply();

            } else {

                color.edit().putString("colourValue","#000000").apply();

            }

            list_content.setTextColor(Color.parseColor(colourValue));

        }
    });

    return view;

}

I have two problems. First, when I click on my item, the color wont always change back and forth. And the second, the color won't save when I switch fragments/close and open the app. How do I fix this?

1 Answers
Related