1.application初始化
public class MApplication extends Application {
private static Editor editor;
private static SharedPreferences sp;
private static DecimalFormat format;
@Override
public void onCreate() {
super.onCreate();
initImageLoaderConfig();
}
// 初始化ImageLoader
private void initImageLoaderConfig() {
String cacheDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ybs/imageloader";
File cacheFile = new File(cacheDir);
if (!cacheFile.exists())
cacheFile.mkdir();
ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(getApplicationContext());
config.threadPriority(Thread.MIN_PRIORITY + 2);
config.denyCacheImageMultipleSizesInMemory();
config.diskCache(new UnlimitedDiscCache(cacheFile));
config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
config.tasksProcessingOrder(QueueProcessingType.LIFO);
config.threadPoolSize(3);
config.writeDebugLogs();
config.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024)).memoryCacheSize(2 * 1024 * 1024);
com.nostra13.universalimageloader.utils.L.disableLogging();
// Initialize ImageLoader with configuration.
// config.imageDownloader(new
// BaseImageDownloader(getApplicationContext(), 300, readTimeout))
ImageLoader.getInstance().init(config.build());
}
}
2.viewpager adapter中的配置
package com.service.ybs.adapter;
import java.io.File;
import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import com.bft.net.state.listener.NetWorkUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.service.ybs.MApplication;
import com.service.ybs.R;
import com.service.ybs.activity.BannerBodyActivity;
import com.service.ybs.constants.Constants;
import com.service.ybs.dialog.MProgressDialog;
import com.service.ybs.entity.home.Advertisement;
import com.service.ybs.httputil.HttpData;
import com.service.ybs.httputil.HttpListener;
import com.service.ybs.httputil.HttpResult;
import com.service.ybs.httputil.NetTool;
import com.service.ybs.httputil.NetTool.MAsyncTask;
import com.service.ybs.utils.Utils;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class ViewPagerAdapter extends PagerAdapter {
/**
* 图片资源列表
*/
private ArrayList
private ArrayList
private Context context;
private DisplayImageOptions mOptions;
private MAsyncTask task;
private MProgressDialog progressDialog;
@SuppressWarnings("deprecation")
public ViewPagerAdapter(Context context, ArrayList
this.context = context;
this.mAdList = adList;
mOptions = new DisplayImageOptions.Builder()
.showImageOnFail(R.drawable.banner1)
.showImageOnLoading(R.drawable.banner1)
.cacheInMemory(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.resetViewBeforeLoading(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true).build();
progressDialog = new MProgressDialog(context);
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if (task != null && task.getStatus() == AsyncTask.Status.RUNNING) {
task.cancel(true);
}
}
});
}
@Override
public int getCount() {
return mAdList.size();
}
@Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
@Override
public Object instantiateItem(ViewGroup container, final int position) {
final Advertisement advert = mAdList.get(position);
// Log.i("tag", "adapter url="+advert.getImgUrl());
View view = LayoutInflater.from(context).inflate(R.layout.header_viewpager, null);
final ImageView imageView = (ImageView) view.findViewById(R.id.header_imageview);
// 设置图片点击监听
/*
* if (position % mAdList.size() == 0) {
* imageView.setOnClickListener(new OnClickListener() {
*
* @Override public void onClick(View v) {
* Utils.showToast("点击了小车生活",context);
*
* Intent it = new Intent(mContext, WebviewActivity.class);
* it.putExtra(WebviewActivity.URL_KEY, advert.getUrl());
* mContext.startActivity(it);
*
* } }); }
*/
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String id = advert.getId();
// Log.i("tag", "adapter id="+id);
if (NetWorkUtil.isNetworkConnected(context)) {
sendBannerBodyRequest(id, advert);
} else {
Utils.showToast(Constants.ToastText.NETWORK_BAD, context);
}
}
});
ImageLoader.getInstance().displayImage(advert.getImgUrl(), imageView, mOptions,
new SimpleImageLoadingListener() {
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
super.onLoadingFailed(imageUri, view, failReason);
// 加载失败时的处理
Log.i("tag", "加载失败时的处理 imageUri=" + imageUri);
}
});
/*
* /storage/emulated/0/ybs/imageloader/-2115343207
* /storage/emulated/0/ybs/imageloader/-2117195953
* /storage/emulated/0/ybs/imageloader/-2116272432
*/
File file=ImageLoader.getInstance().getDiscCache().get(advert.getImgUrl());
if(file!=null){
String cachePath=file.getPath();
if(cachePath!=null)
MApplication.putString("viewPagerImageCachePath", cachePath);
//Log.e(getClass().getName(), "viewPagerImageCachePath 缓存 路径=="+cachePath);
// ArrayList
// for(int i=0;i
// }
}
mAdView.add(view);
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// 这里不需要做任何事情
}
private void sendBannerBodyRequest(String id, final Advertisement advert) {
progressDialog.show();
JSONObject obj = new JSONObject();
HttpData httpData = new HttpData();
try {
obj.put("id", id);
} catch (JSONException e1) {
e1.printStackTrace();
}
httpData.setBody(obj.toString());
httpData.setUrl(Constants.BANNER_IMAGE_BODY_URL);
HttpListener listener = new HttpListener() {// TODO
@Override
public void onResult(HttpResult result) {
progressDialog.dismiss();
if (result == null) {
Utils.showToast("请求失败了,请稍后重试!", context);
return;
}
switch (result.getHttpStatus()) {
case HTTP_OK:
String content = result.getResult();
Log.i("tag", "图片点击监听content==" + content);
try {
JSONObject objs = new JSONObject(content);
String respCode = objs.getString("respCode");
if (Constants.returnSucceed.equals(respCode)) {
String contents = objs.getString("bannerInfo");
Intent it = new Intent(context, BannerBodyActivity.class);
it.putExtra("htmlUrl", contents);
it.putExtra("title", advert.getTitle());
context.startActivity(it);
}else{
Utils.showToast(objs.getString("respMsg"), context);
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
case HTTP_ERR:
Utils.showToast("获取数据失败,请稍后重试", context);
break;
default:
break;
}
}
};
task = NetTool.loadData(httpData, listener);
}
}
3.activity中的调用
package com.service.ybs.fragment.impl;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.bft.net.state.listener.NetWorkUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.service.ybs.MApplication;
import com.service.ybs.R;
import com.service.ybs.activity.customerservice.OnLineCustomerActivity;
import com.service.ybs.activity.trans.QueryPosActivity;
import com.service.ybs.adapter.FristFragmentAdapter;
import com.service.ybs.adapter.ViewPagerAdapter;
import com.service.ybs.constants.Constants;
import com.service.ybs.dialog.MProgressDialog;
import com.service.ybs.entity.PersonMsg;
import com.service.ybs.entity.home.Advertisement;
import com.service.ybs.entity.home.FristFragmentBean;
import com.service.ybs.fragment.BaseFragment;
import com.service.ybs.httputil.HttpData;
import com.service.ybs.httputil.HttpListener;
import com.service.ybs.httputil.HttpResult;
import com.service.ybs.httputil.NetTool;
import com.service.ybs.httputil.NetTool.MAsyncTask;
import com.service.ybs.utils.HelperUtils;
import com.service.ybs.utils.SaveList;
import com.service.ybs.utils.Utils;
import com.service.ybs.widget.LoopViewPager;
/**
* 首页
*
*
*
*/
public class HomePageFragment extends BaseFragment implements OnItemClickListener {
private static final String TAG = "HomePageFragment.class";
private List
private LoopViewPager viewPager;
private List
private MProgressDialog progressDialog;
private MAsyncTask task;
private ArrayList
private LinearLayout indicatorLayout;
private static HomePageFragment instance;
private String picContent=null;
/** 记录上一个点的位置 */
private int prePos = 0;// 0
private Object bitmap;
// 单例模式
public static HomePageFragment newInstance() {
if (instance == null) {
instance = new HomePageFragment();
}
return instance;
}
@Override
public int setResId() {
return R.layout.activity_person_msg;
}
@Override
public void initView() {
progressDialog = new MProgressDialog(mActivity);
progressDialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
if (task != null && task.getStatus() == AsyncTask.Status.RUNNING) {
task.cancel(true);
}
}
});
// 广告轮询相关
initViewPager();
}
// 广告轮询条事件*********************************************************************************************
private void initViewPager() {
// 呈现viewPager及页面指示器的布局
adverList = new ArrayList
indicatorLayout = (LinearLayout) view.findViewById(R.id.dotLayout);
Log.i("tag", "indicatorLayout==" + indicatorLayout.toString());
viewPager = (LoopViewPager) view.findViewById(R.id.viewpager);
String ImCachePath = MApplication.gettString("fileCachePaths", null);
if(ImCachePath!=null){
Log.e("tag", "HomePageFragment保存起来的viewpager 缓存文件路径=="+ImCachePath);
List
if(piclists!=null&&piclists.size()!=0){
Log.e("tag", "HomePageFragment保存起来的viewpager 缓存文件中的list=="+piclists.toString());
viewPager.setAdapter(new ViewPagerAdapter(mActivity, (ArrayList
// 如果图片在最后一张跳转时有闪烁,可以设置为TURE
viewPager.setBoundaryCaching(true);
// 页面指示器的点
setIndicatorShow(indicatorLayout,(ArrayList
}else{
downLoadBannerImageEvent();
}
}else{
downLoadBannerImageEvent();
}
}
private void downLoadBannerImageEvent() {
if (NetWorkUtil.isNetworkConnected(mActivity)) {
sendImageRequest();
} else {
Utils.showToast(Constants.ToastText.NETWORK_BAD, mActivity);
}
}
private void sendImageRequest() {
progressDialog.show();
JSONObject obj = new JSONObject();
HttpData httpData = new HttpData();
try {
obj.put("type", "00");
} catch (JSONException e1) {
e1.printStackTrace();
}
httpData.setBody(obj.toString());
httpData.setUrl(Constants.FRIST_BANNER_IMAGE);
HttpListener listener = new HttpListener() {
@Override
public void onResult(HttpResult result) {
progressDialog.dismiss();
if (result == null) {
Utils.showToast("请求失败了,请稍后重试!", mActivity);
return;
}
switch (result.getHttpStatus()) {
case HTTP_OK:
String content = result.getResult();
Log.i("tag", "type00 content==" + content);
try {
JSONObject objs = new JSONObject(content);
String respCode = objs.getString("respCode");
if (Constants.returnSucceed.equals(respCode)) {
JSONArray ary = objs.getJSONArray("bannerList");
for (int i = 0; i < ary.length(); i++) {
JSONObject obj1 = (JSONObject) ary.get(i);
String url=obj1.getString("titleImg");
Log.i("tag","请求的图片1 url=="+url);
Advertisement advertisement = new Advertisement();
advertisement.setId(obj1.getString("id"));
advertisement.setSort(obj1.getInt("sort"));
advertisement.setImgUrl(url);
advertisement.setTitle(obj1.getString("title"));
adverList.add(advertisement);
// Log.i("tag",
// "advertisement=="+advertisement);
// Log.i("tag", "adverList=="+adverList);
// Log.i("tag","请求的图片2 url=="+advertisement.getImgUrl());
}
Collections.sort(adverList, new Comparator
@Override
public int compare(Advertisement lhs, Advertisement rhs) {
return lhs.getSort() - rhs.getSort();
}
});
File file=SaveList.setSaveList(adverList, "homePageImage");
MApplication.putString("fileCachePaths", file.getAbsolutePath());
// Log.i("tag", "adverList=="+adverList.toString());
// Log.i("tag","请求的图片size=="+adverList.size());
viewPager.setAdapter(new ViewPagerAdapter(mActivity, adverList));
// 如果图片在最后一张跳转时有闪烁,可以设置为TURE
viewPager.setBoundaryCaching(true);
// 页面指示器的4个点
setIndicatorShow(indicatorLayout,adverList);
}else{
Utils.showToast(objs.getString("respMsg"), mActivity);
ArrayList
if(adverList1.size()!=0){
viewPager.setAdapter(new ViewPagerAdapter(mActivity, adverList1));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
break;
case HTTP_ERR:
Utils.showToast("获取数据失败,请稍后重试", mActivity);
// List
// Log.e("tag", "取出来的url list=="+picList);
// viewPager.setAdapter(new ViewPagerAdapter(mActivity, (ArrayList
ArrayList
if(adverList1.size()!=0){
viewPager.setAdapter(new ViewPagerAdapter(mActivity, adverList1));
}
break;
default:
break;
}
}
};
task = NetTool.loadData(httpData, listener);
}
private void setIndicatorShow(final LinearLayout indicatorLayout,ArrayList
for (int i = 0; i < adverList1.size(); i++) {
View v = new View(mActivity);
v.setEnabled(false);
v.setBackgroundResource(R.drawable.pager_indicator_selector_1);
LayoutParams params = new LayoutParams(15, 15);
params.rightMargin = 10;
v.setLayoutParams(params);
indicatorLayout.addView(v);
}
// 设置默认第一个点为亮点
indicatorLayout.getChildAt(0).setEnabled(true);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int pos) {
//Log.i("tag", "pos==" + pos);
View views = indicatorLayout.getChildAt(pos);
views.setEnabled(true);// 显示白点
indicatorLayout.getChildAt(prePos).setEnabled(false);// 显示黑点
prePos = pos;
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
}