利用sharePrefences记录被点击的ListView

点击过的ListVIew 被记录,并把title变为灰色

效果图:

利用sharePrefences记录被点击的ListView_第1张图片


1 封装SharePrefences:

/*
 * 封装sharePreferences 
 */
public class PreferenceUtils {

	public final static String PREF_NAME="config";
	public 	static String getString(Context ctx,String key,String defaultValue)
	{
		SharedPreferences sp=ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
		
		return sp.getString(key, defaultValue);
		
	}
	public 	static void SetString(Context ctx,String key,String defaultValue)
	{
		SharedPreferences sp=ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
		
		sp.edit().putString(key, defaultValue).commit();
	}
}


2 添加listView监听:

lv_tablist.setOnItemClickListener(new OnItemClickListener() {//监听哪一个被点击,并将点击的条目变灰色

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				position=position-lv_tablist.getHeaderViewsCount();
				
				
				System.out.println(position+"  : "+view);
				//changeReadState(view);	//直接调用的弊端,由于是优化过的ListView 因此不是重复绘制ListView,一个被标记时会出现多个ListView变灰色的情况		
			
				/*
				 * 可使用sharePreference来记录被点击的ID
				 */
				String ids = PreferenceUtils.getString(mActivity, "read_ids", "");
				
				if(!ids.contains(mNewsList.get(position).id))
				{
					ids=ids+mNewsList.get(position).id+" ,";
					PreferenceUtils.SetString(mActivity, "read_ids", ids);
				}
				mNewsdapger.notifyDataSetChanged();
			}
		});


3 刷新ListVIew:

使用notifyDataSetChanged之后,在适配器getView中添加:

/*
			 * 获取被点击ListView 的ID,并变换Title的颜色
			 */
			String ids=PreferenceUtils.getString(mActivity, "read_ids", "");
			if(ids.contains(getItem(position).id))
			{
				holder.ViewHolder_tvTitle.setTextColor(Color.GRAY);
			}
			else
			{
				holder.ViewHolder_tvTitle.setTextColor(Color.BLACK);
			}



你可能感兴趣的:(android,项目)