所以在我的应用程序中。我正在显示来自服务器的通知。在开始时,它们都是蓝色的,但当点击其中任何一个时,它的颜色变成灰色。我已经使用setColor
方法处理了这个问题。但问题是每当我关闭我的应用并再次启动它时,它都具有相同的默认(Blue
)颜色。我想为点击的(Read
)一个通知保留灰色。我已经使用了SharedPreferences
,但它对我不起作用。以下是我的代码。如果有人有任何代码示例或任何想法,请帮助我。提前谢谢。
这是我的适配器代码,我设置并获取SharedPreferences
值:
private static SharedPreferences mSharedPreferences;
ArrayList<ReadNotifications> listDtails;
public AdatperReadNotification(Context context , ArrayList<ReadNotifications> save) {
this.context = context;
this.listDtails = save;
}
@Override
public View getView(final int position, View view , ViewGroup arg2) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
{
view = inflater.inflate(R.layout.adapter_readnotificaiton, null);
}
mSharedPreferences = context.getSharedPreferences(
"MyPref", 0);
ReadNotifications details = listDtails.get(position);
final TextView date = (TextView) view.findViewById(R.id.date);
RelativeLayout re=(RelativeLayout) view.findViewById(R.id.relayout);
boolean state = mSharedPreferences.getBoolean("true", true);
int pos = mSharedPreferences.getInt("position", -1);
if(state!=true)
{
date.setId(pos);
date.setTextColor(Color.GRAY);
}
else{
date.setTextColor(Color.rgb(0,255,255));
}
date.setText(details.tvText());
re.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
date.setTextColor(Color.GRAY);
Editor e = mSharedPreferences.edit();
e.putInt("position", position);
e.putBoolean("true", true);
e.commit(); // save changes
Intent intent = new Intent(context,NewNotification.class);
v.getContext().startActivity(intent);
listDtails.get(position).isSelected = true;
}
});
return view;
}
这是我的ReadNotifications类:
public class ReadNotifications implements Serializable
{
public boolean isSelected;
ContentValues colmnValues;
public ReadNotifications(ContentValues values )
{
colmnValues = values;
}
public String tvText() {
return getValue(colmnValues.get("tvText"));
}
private String getValue(Object obj){
if(obj == null){
return "";
}
return (String) obj;
}
}
EDITED:
在SharedPref
稍微改变之后它有效但现在问题出现了,当我选择第二个通知时,它将第一个通知的颜色变为蓝色,将第二个颜色更改为灰色。当我杀了我的应用程序时会发生这是改变
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
而不是
/*mSharedPreferences = context.getSharedPreferences(
"MyPref", 0);*/
和
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putInt("position", position);
e.putInt("true", 11);
e.commit(); // save changes
和if condition
现在看起来像
int state = mSharedPreferences.getInt("true", 0);
int pos = mSharedPreferences.getInt("position", 0);
if(state==11 && pos==position)
{
date.setTextColor(Color.GRAY);
}