缓存使用key-value的形式,key是json的url,value是json的内容。将缓存保存在SharedPreference中,也可以把缓存保存在文件中,文件名就是url(MD5的形式),文件的内容是json
创建一个工具,将内容保存在SharedPreference中
package com.ldw.beijing.utils;
import android.content.Context;
/*
* 图片的缓存工具类
*/
public class CacheUtils {
//设置缓存,key:是url。value是json的内容
//也可以把缓存保存在文件中,文件名就是url(MD5的形式),文件的内容是json
public static void setCache(String key, String json, Context context){
PreferencesUtils.setString(context, key, json);
}
//获取缓存
public static String getCache(String key, Context context){
return PreferencesUtils.getString(context, key, null);
}
}
设置缓存和读取缓存NewsCenterPager
package com.ldw.beijing.base.impl;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.ldw.beijing.MainActivity;
import com.ldw.beijing.base.BaseMenuDetailPager;
import com.ldw.beijing.base.BasePager;
import com.ldw.beijing.base.menudetails.InteractMenuDetailPager;
import com.ldw.beijing.base.menudetails.NewsMenuDetailPager;
import com.ldw.beijing.base.menudetails.PhotoMenuDetailPager;
import com.ldw.beijing.base.menudetails.TopicMenuDetailPager;
import com.ldw.beijing.domain.NewsData;
import com.ldw.beijing.domain.NewsData.NewsMenuData;
import com.ldw.beijing.fragment.LeftMenuFragment;
import com.ldw.beijing.global.ClobalContants;
import com.ldw.beijing.utils.CacheUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
/**
* 新闻中心
*
* @author Kevin
*
*/
public class NewsCenterPager extends BasePager {
// 4个菜单详情页的集合,填充左侧菜单栏对应的ViewPager中的详情
private ArrayList<BaseMenuDetailPager> mPagers;
private NewsData mNewsData;
public NewsCenterPager(Activity activity) {
super(activity);
}
@Override
public void initData() {
System.out.println("初始化设置数据....");
tvTitle.setText("新闻");
//btnMenu.setVisibility(View.GONE);// 隐藏菜单按钮
setSlidingMenuEnable(true);// 关闭侧边栏
/*
TextView text = new TextView(mActivity);
text.setText("设置");
text.setTextColor(Color.RED);
text.setTextSize(25);
text.setGravity(Gravity.CENTER);
// 向FrameLayout中动态添加布局
flContent.addView(text);
*/
//读取缓存,
String cache = CacheUtils.getCache(ClobalContants.CATEGORIES_URL, mActivity);
if(!TextUtils.isEmpty(cache)){
//缓存存在,直接解析数据,不需要从服务器读取
parseData(cache);
}
//从服务器中获取数据,从后台可以更新数据
getDataFromServer();
}
/*
* 从服务器中获取数据,使用xUtils实现
*/
private void getDataFromServer(){
HttpUtils utils = new HttpUtils();
//参数是String获取到的是String
utils.send(HttpMethod.GET, ClobalContants.CATEGORIES_URL, new RequestCallBack<String>(){
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
//获取到返回的结果
String result = (String) responseInfo.result;
System.out.println("返回结果:" + result);
parseData(result);
//设置缓存
CacheUtils.setCache(ClobalContants.CATEGORIES_URL, result, mActivity);
}
//访问失败
@Override
public void onFailure(HttpException error, String msg) {
Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT)
.show();
//打印错误信息
error.printStackTrace();
}
});
}
/*
* 解析网络数据
*/
protected void parseData(String result) {
//使用Gson解析
Gson gson = new Gson();
//第一个参数是数据,第二个参数是要转化成什么对象
mNewsData = gson.fromJson(result, NewsData.class);
System.out.println("解析结果:" + mNewsData);
// 刷新测边栏的数据,利用MainActivity获取到左侧边栏的数据
MainActivity mainUi = (MainActivity) mActivity;
//获取到左侧边栏的对象
LeftMenuFragment leftMenuFragment = mainUi.getLeftMenuFragment();
//设置网络数据
leftMenuFragment.setMenuData(mNewsData);
//设置4个菜单详情页,LeftMenuFragment和内容的交互,需要调用这里的方法,来初始化侧边栏对应的内容
mPagers = new ArrayList<BaseMenuDetailPager>();
//获取到data条目下面,news对于页面的children数据,初始化详情页的构造函数
mPagers.add(new NewsMenuDetailPager(mActivity, mNewsData.data.get(0).children));
mPagers.add(new TopicMenuDetailPager(mActivity));
mPagers.add(new PhotoMenuDetailPager(mActivity));
mPagers.add(new InteractMenuDetailPager(mActivity));
// 设置菜单详情页-新闻为默认当前页
setCurrentMenuDetailPager(0);
}
//设置当前的菜单详情页,显示哪一个详情页,LeftMenuFragment和内容的交互
public void setCurrentMenuDetailPager(int position){
//获取到某一个位置的pager
BaseMenuDetailPager pager = mPagers.get(position);
// 清除之前的布局,fragment布局的内容会叠加
flContent.removeAllViews();
//填充内容,mRebootView就是初始化的某一个子页面,设置给frameLayout
flContent.addView(pager.mRebootView);
// 设置当前页的标题
NewsMenuData menuData = mNewsData.data.get(position);
tvTitle.setText(menuData.title);
// 初始化当前页面的数据
pager.initData();
}
}
TabDetailPager.java图片的刷新
package com.ldw.beijing.base;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.ldw.beijing.NewDetailActivity;
import com.ldw.beijing.R;
import com.ldw.beijing.domain.TabData;
import com.ldw.beijing.domain.NewsData.NewsTabData;
import com.ldw.beijing.domain.TabData.TabNewsData;
import com.ldw.beijing.domain.TabData.TopNewsData;
import com.ldw.beijing.global.ClobalContants;
import com.ldw.beijing.utils.CacheUtils;
import com.ldw.beijing.utils.PreferencesUtils;
import com.ldw.beijing.view.RefreshListView;
import com.ldw.beijing.view.RefreshListView.OnRefreshListener;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.viewpagerindicator.CirclePageIndicator;
/*
* 左边菜单栏右边详情页,最上面对应的tab,页签
*/
public class TabDetailPager extends BaseMenuDetailPager implements OnPageChangeListener{
//携带数据详情的数据
private NewsTabData mTabData;
private TextView text;
private String mUrl;
private TabData mTabDetailData;
@ViewInject(R.id.vp_news)
private ViewPager mViewPager;
@ViewInject(R.id.tv_title)
private TextView tv_title;//banner的标题
@ViewInject(R.id.indicator)
private CirclePageIndicator indicator;//banner下面的小圆点
@ViewInject(R.id.lv_list)
private RefreshListView lv_list;//新闻列表
private ArrayList<TopNewsData> mTopNewsList;//banner的数据
private ArrayList<TabNewsData> mNewsList;
private String mMoreUrl;//加载更多的链接地址
private NewsAdapter mNewsAdapter;
public TabDetailPager(Activity activity, NewsTabData newsTabData) {
super(activity);
mTabData = newsTabData;
//图片的地址
mUrl = ClobalContants.SERVER_URL + mTabData.url;
}
@Override
public View initView() {
View view = View.inflate(mActivity, R.layout.tab_detail_pager, null);
//把banner添加到ListView的头部,实现二者的组合
View headView = View.inflate(mActivity, R.layout.list_header_topnews, null);
ViewUtils.inject(this, view);
ViewUtils.inject(this, headView);
//添加到ListView的头部
lv_list.addHeaderView(headView);
//监听下拉刷新,调用自定义布局中的接口
lv_list.setOnRefreshListener(new OnRefreshListener(){
@Override
public void onRefresh() {
//读取数据
getDataFromServer();
//结束刷新
lv_list.onRefreshComplete(true);
}
@Override
public void onLoadMore() {
if(mMoreUrl != null){
getMoreDataFromServer();
}else{
Toast.makeText(mActivity, "最后一条了", Toast.LENGTH_SHORT).show();
//隐藏脚部局
lv_list.onRefreshComplete(false);
}
}
});
//将读取过的数据保存给lv_list添加点击事件,监听点击,在RefreshListView中进行了封装返回了position-2
lv_list.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
System.out.println("点击:"+ position);
//获取到保存的read_ids对象
String ids = PreferencesUtils.getString(mActivity, "read_ids", "");
String readId =mNewsList.get(position).id;
//不包含在PreferencesUtils中添加记录中
if(!ids.contains(readId)){
//将读取到点击的id保存,同时在后面添加一个","
ids = ids + readId + ",";
//保存数据
PreferencesUtils.setString(mActivity, "read_ids", ids);
}
//刷新UI来修改文本的颜色,方法耗内存会全局刷新,使用changeReadState
//mNewsAdapter.notifyDataSetChanged();
changeReadState(view);//局部界面刷新,针对点击的view刷新
//点击新闻跳转到新闻的详情页
Intent intent = new Intent();
intent.setClass(mActivity, NewDetailActivity.class);
intent.putExtra("url", mNewsList.get(position).url);
mActivity.startActivity(intent);
//mActivity.startActivity(new Intent(mActivity, NewDetailActivity.class));
}
});
//监听Viewager的滑动
//mViewPager.setOnPageChangeListener(this);
// 向FrameLayout中动态添加布局
return view;
}
/*
* 修改已读新闻的颜色
*/
private void changeReadState(View view){
TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
tv_title.setTextColor(Color.GRAY);
}
@Override
public void initData(){
//读取缓存,
String cache = CacheUtils.getCache(mUrl, mActivity);
if(!TextUtils.isEmpty(cache)){
//缓存存在,直接解析数据,不需要从服务器读取
parseData(cache, false);
}
//从服务器更新数据
getDataFromServer();
}
/*
* 获取网络数据
*/
private void getDataFromServer() {
//从服务器中获取数据
HttpUtils utils = new HttpUtils();
utils.send(HttpMethod.GET, mUrl, new RequestCallBack<String>(){
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
//获取到返回的结果
String result = (String) responseInfo.result;
System.out.println("tab详情返回结果:" + result);
parseData(result, false);
//隐藏布局
lv_list.onRefreshComplete(true);
//设置缓存
CacheUtils.setCache(mUrl, result, mActivity);
}
@Override
public void onFailure(HttpException error, String msg) {
Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT)
.show();
//打印错误信息
error.printStackTrace();
}
});
}
/*
* 获取更多网络数据
*/
private void getMoreDataFromServer() {
//从服务器中获取数据
HttpUtils utils = new HttpUtils();
utils.send(HttpMethod.GET, mMoreUrl, new RequestCallBack<String>(){
@Override
public void onSuccess(ResponseInfo<String> responseInfo) {
//获取到返回的结果
String result = (String) responseInfo.result;
System.out.println("tab详情返回结果:" + result);
parseData(result, true);
}
@Override
public void onFailure(HttpException error, String msg) {
Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT)
.show();
//打印错误信息
error.printStackTrace();
}
});
}
/*
* 解析网络数据,第二个参数表示是否加载下一页
*/
protected void parseData(String result,boolean isMore) {
//使用Gson解析
Gson gson = new Gson();
mTabDetailData = gson.fromJson(result, TabData.class);
System.out.println("解析结果:" + mTabDetailData);
//服务器读取加载更多数据
String more = mTabDetailData.data.more;
if(!TextUtils.isEmpty(more)){
mMoreUrl = ClobalContants.SERVER_URL + more;
}else{
mMoreUrl = null;
}
//不加载更多
if(!isMore){
//新闻列表的数据ListView
mNewsList = mTabDetailData.data.news;
//取到banner新闻top的数据
mTopNewsList = mTabDetailData.data.topnews;
//top新闻填充
if(mTopNewsList != null){
//填充top新闻的pagre
mViewPager.setAdapter(new TopNewsAdapter());
//banner下面的小圆点,需要在adapter初始化以后才能显示
indicator.setViewPager(mViewPager);
indicator.setSnap(true);//支持快照显示
indicator.setOnPageChangeListener(this);//添加监听,修改文本内容
indicator.onPageSelected(0);//默认选择第一个,防止图片和远点不对应
//解析数据的时候初始化标题
tv_title.setText(mTopNewsList.get(0).title);
}
//填充新闻列表
if(mNewsList != null){
mNewsAdapter = new NewsAdapter();
lv_list.setAdapter(mNewsAdapter);
}
}else{
//是加载下一页,需要吧数据追加到原来的集合
ArrayList<TabNewsData> news = mTabDetailData.data.news;
mNewsList.addAll(news);
//数据发生改变
mNewsAdapter.notifyDataSetChanged();
}
}
/*
* 头条新闻,banner
*/
class TopNewsAdapter extends PagerAdapter{
private BitmapUtils utils;
//构造函数
public TopNewsAdapter(){
utils = new BitmapUtils(mActivity);
//加载数据过程中,设置默认加载的图片
utils.configDefaultLoadingImage(R.drawable.topnews_item_default);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mTabDetailData.data.topnews.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
//初始化banner图
ImageView image = new ImageView(mActivity);
//填充布局对象
//image.setImageResource(R.drawable.topnews_item_default);
//填充平铺布局,基于控件的大小
image.setScaleType(ScaleType.FIT_XY);
//获取到图片资源的数据的地址
TopNewsData topNewsData = mTabDetailData.data.topnews.get(position);
utils.display(image, topNewsData.topimage);
//添加image数据
container.addView(image);
return image;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
//新闻列表的适配器
class NewsAdapter extends BaseAdapter{
private BitmapUtils utils;
//构造函数初始化图片
public NewsAdapter(){
utils = new BitmapUtils(mActivity);
//加载的时候显示默认图片
utils.configDefaultLoadingImage(R.drawable.pic_item_list_default);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return mNewsList.size();
}
@Override
public TabNewsData getItem(int position) {
// TODO Auto-generated method stub
return mNewsList.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = View.inflate(mActivity, R.layout.list_news_item, null);
holder = new ViewHolder();
holder.iv_pic = (ImageView) convertView.findViewById(R.id.iv_pic);
holder.tv_date = (TextView) convertView.findViewById(R.id.tv_date);
holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
TabNewsData item = (TabNewsData) getItem(position);
holder.tv_title.setText(item.title);
holder.tv_date.setText(item.pupdate);
utils.display(holder.iv_pic, item.listimage);
//读取保存的ids,将读取过的listView颜色修改
String ids = PreferencesUtils.getString(mActivity, "read_ids", "");
if(ids.contains(getItem(position).id)){
holder.tv_title.setTextColor(Color.GRAY);
}
return convertView;
}
}
static class ViewHolder{
public TextView tv_title;
public TextView tv_date;
public ImageView iv_pic;
}
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
// TODO Auto-generated method stub
}
//滑动的监听,当页面被选中的时候更新标题
@Override
public void onPageSelected(int position) {
//TopNewsData topNewsData= mTabDetailData.data.topnews.get(position);
tv_title.setText(mTopNewsList.get(position).title);
}
@Override
public void onPageScrollStateChanged(int state) {
// TODO Auto-generated method stub
}
}