使用sharedPreferences在listView中保存textView颜色

时间:2017-06-01 20:07:38

标签: android listview sharedpreferences

我有listView和片段中的自定义适配器,它只包含一个名为list_content的textView。我希望用户更改textView onClick的颜色。到目前为止,这是我的相关代码onCreate以及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;

}

我有两个问题。首先,当我点击我的项目时,颜色不会总是来回变化。第二,当我切换片段/关闭并打开应用程序时,颜色不会保存。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

因此,当你启动应用程序时,似乎加载colourValue共享pref,但它不会立即对它做任何事情。看起来,当您单击时,它将使用共享首选项中保存的最后一个colourValue,但与应用程序启动时创建的视图状态无关。也许您需要加载此colourValue并在启动时将其应用于列表视图?如果要保存每个列表视图项的状态,则需要多做一些工作并保存整个列表的状态。不确定共享首选项是否容易。也许创建一个状态对象并将其序列化为GSON并使用Gson或其他东西将其存储到共享的pref中。

我认为这里有一点太多了,你可能想在尝试保持列表的颜色状态之前先尝试使用它。确保切换打开和关闭。

我认为,这里的另一个问题是你为这种颜色状态管理了一个值,但你的列表中可能有多个项目。如果我多次单击第一个项目,它可能会切换,但如果我单击第二个项目,它将根据第一个项目所处的状态进行切换(因为它使用共享首选项中保存的值)时间)。

另外,我没有看到你调用SharedPreferences commit():https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#commit()

相关问题