2017-06-01 74 views
1

我有listView和片段中的自定义适配器,其中只包含一个名为list_content的textView。我希望用户改变textView onClick的颜色。到目前为止,这是我的相关代码onCreate与listView setOnItemClickedListener一起:使用sharedPreferences在listView中保存textView颜色

@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

所以,当你启动应用程序似乎加载colourValue共享pref,但它不会立即做任何事情。它看起来像点击时,它会使用共享偏好设置中保存的最后一个colourValue,但与您在应用启动时创建的视图状态无关。也许你需要加载这个colourValue并在开始时将它应用到列表视图中?如果你想保存每个列表视图项的状态,你需要做更多的工作并保存整个列表的状态。不知道共享首选项是否容易。也许创建一个状态对象并将其序列化成GSON并使用Gson或其他东西将它存储到共享的pref中。

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

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

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

+0

你的答案清除它颇有几分。我猜sharedPreferences不会真的做到这一点,我会尝试其他方法。谢谢。 – Zeo