您的位置:首页 > 其它

使用MVP搜索页面到商品列表与商品详情

2017-12-17 19:43 459 查看
//molder文件夹下_Mymolder

public class Mymodel {
private  Mjiekou jie;

public Mymodel(Mjiekou mjiekou) {
this.jie=mjiekou;
}
public void getdata(String url){
OkUrl.doget(url, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}

@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
String string = response.body().string();
jie.chneggong(string);
}
}
});
}
}


//Mjiekou

public interface Mjiekou {
void chneggong(String json);
}


//presenter文件夹下_Mypresenter

public class Mypresent implements Mjiekou {
private  Pjiekou jie;
private Mymodel mymodel;

public Mypresent(Pjiekou pjiekou) {
this.jie=pjiekou;
mymodel = new Mymodel(this);
}
public void geturl(String url){
mymodel.getdata(url);
}

@Override
public void chneggong(String json) {
jie.chneggong(json);
}
}


//utils文件夹下_Flow.java

public class flow extends ViewGroup {
//存储所有子View
private List<List<View>> mAllChildViews = new ArrayList<>();
//每一行的高度
private List<Integer> mLineHeight = new ArrayList<>();

public flow(Context context) {
this(context, null);
}

public flow(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public flow(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//父控件传进来的宽度和高度以及对应的测量模式
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
//如果当前ViewGroup的宽高为wrap_content的情况
int width = 0;//自己测量的 宽度
int height = 0;//自己测量的高度
//记录每一行的宽度和高度
int lineWidth = 0;
int lineHeight = 0;

//获取子view的个数
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
//测量子View的宽和高
measureChild(child, widthMeasureSpec, heightMeasureSpec);
//得到LayoutParams
MarginLayoutParams lp = (MarginLayoutParams) getLayoutParams();
//子View占据的宽度
int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
//子View占据的高度
int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
//换行时候
if (lineWidth + childWidth > sizeWidth) {
//对比得到最大的宽度
width = Math.max(width, lineWidth);
//重置lineWidth
lineWidth = childWidth;
//记录行高
height += lineHeight;
lineHeight = childHeight;
} else {//不换行情况
//叠加行宽
lineWidth += childWidth;
//得到最大行高
lineHeight = Math.max(lineHeight, childHeight);
}
//处理最后一个子View的情况
if (i == childCount - 1) {
width = Math.max(width, lineWidth);
height += lineHeight;
}
}
//wrap_content
setMeasuredDimension(modeWidth == MeasureSpec.EXACTLY ? sizeWidth : width,
modeHeight == MeasureSpec.EXACTLY ? sizeHeight : height);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
mAllChildViews.clear();
mLineHeight.clear();
//获取当前ViewGroup的宽度
int width = getWidth();

int lineWidth = 0;
int lineHeight = 0;
//记录当前行的view
List<View> lineViews = new ArrayList<View>();
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int childWidth = child.getMeasuredWidth();
int childHeight = child.getMeasuredHeight();

//如果需要换行
if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width) {
//记录LineHeight
mLineHeight.add(lineHeight);
//记录当前行的Views
mAllChildViews.add(lineViews);
//重置行的宽高
lineWidth = 0;
lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
//重置view的集合
lineViews = new ArrayList();
}
lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
lineViews.add(child);
}
//处理最后一行
mLineHeight.add(lineHeight);
mAllChildViews.add(lineViews);

//设置子View的位置
int left = 0;
int top = 0;
//获取行数
int lineCount = mAllChildViews.size();
for (int i = 0; i < lineCount; i++) {
//当前行的views和高度
lineViews = mAllChildViews.get(i);
lineHeight = mLineHeight.get(i);
for (int j = 0; j < lineViews.size(); j++) {
View child = lineViews.get(j);
//判断是否显示
if (child.getVisibility() == View.GONE) {
continue;
}
MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
int cLeft = left + lp.leftMargin;
int cTop = top + lp.topMargin;
int cRight = cLeft + child.getMeasuredWidth();
int cBottom = cTop + child.getMeasuredHeight();
//进行子View进行布局
child.layout(cLeft, cTop, cRight, cBottom);
left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
}
left = 0;
top += lineHeight;
}
}

/**
* 与当前ViewGroup对应的LayoutParams
*/
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
// TODO Auto-generated method stub
return new MarginLayoutParams(getContext(), attrs);
}
}


//Imagbase

public class Imagbase {
public static void info(Context context){
File cacheDir = StorageUtils.getCacheDirectory(context);  //指定默认的硬盘(sd卡)的缓存文件夹路径

/**
* 可以自己创建一个sd下面的文件夹作为硬盘缓存的路径
*/
File file = new File(Environment.getExternalStorageDirectory(),"image");
if (! file.exists()){
file.mkdirs();
}

//1.创建一个ImageLoaderConfiguration,,,图片加载器的配置对象
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)

.threadPoolSize(3) // default  线程池内加载的数量
.threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级
.tasksProcessingOrder(QueueProcessingType.FIFO) // default
.denyCacheImageMultipleSizesInMemory()

//1 TB = 1024GB 1G=1024MB 1M = 1024KB 1KB = 1024BYTE
//LruMemoryCache,,lru最近最少使用算法...内部维护的是LinkedHashMap,,当一张图片最近很少使用的时候会从mao集合里面移除
.memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //指定内存缓存的大小,,2M,,可以通过自己的内存缓存实现
.memoryCacheSize(2 * 1024 * 1024)  // 内存缓存的最大值
.memoryCacheSizePercentage(13) // default

//指定硬盘/磁盘缓存的路径
.diskCache(new UnlimitedDiskCache(cacheDir)) // default 可以自定义缓存路径
.diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值
.diskCacheFileCount(100)  // 可以缓存的文件数量

.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
.writeDebugLogs() // 打印debug log
.build(); //开始构建

//对上面配置对象的初始化
ImageLoader.getInstance().init(config);
}
/*
* 展示图片
* */
public static DisplayImageOptions getDefaultOption() {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片
.showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
.showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片

.resetViewBeforeLoading(true)  // default 设置图片在加载前是否重置、复位

.cacheInMemory(true) // default  设置下载的图片是否缓存在内存中
.cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中

.considerExifParams(true) // default

.imageScaleType(ImageScaleType.EXACTLY_STRETCHED) // default 设置图片以如何的编码方式显示
.bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型

.displayer(new SimpleBitmapDisplayer()) // default  还可以设置圆角图片new RoundedBitmapDisplayer(20)
.build();

return options;
}
}


//Imagoath

public class Inagoath extends Application {
@Override
public void onCreate() {
super.onCreate();
Imagbase.info(this);
}
}


//OkUrl

public class OkUrl {
//创建全局的okhttp
private  static OkHttpClient okHttpClient=null;
private OkUrl() {
}

//将缓存的路径和超时操作抽成方法
public static OkHttpClient getInstance(){
if(okHttpClient==null){
//加同步安全
synchronized (OkHttpClient.class){
if(okHttpClient==null){
//缓存路径
File secache=new File(Environment.getExternalStorageDirectory(),"cache");

//指定缓存文件大小
int ceche=10*1024*1024;

//创建构造器
okHttpClient = new OkHttpClient.Builder()
//连接超时
.connectTimeout(15, TimeUnit.SECONDS)
//读写超时
.writeTimeout(20,TimeUnit.SECONDS).readTimeout(202,TimeUnit.SECONDS)
.build();
}
}
}
return okHttpClient;
}
/*
* get请求
*  url路径 回调的callbask
* */
public static void doget(String url, Callback callback){
//创建请求对象---对象已经封装好
OkHttpClient okHttpClient=getInstance();
//创建Request
Request request = new Request.Builder().url(url).build();
//得到Call对象
Call call = okHttpClient.newCall(request);
//执行异步请求
call.enqueue(callback);
}
/**
* post请求
* 参数1 url
* 参数2 Map<String, String> params post请求的时候给服务器传的数据
*      add..("","")
*      add()
*/
public static void doPost(String url, Map<String, String> params, Callback callback) {
//创建OkHttpClient请求对象
OkHttpClient okHttpClient = getInstance();
//3.x版本post请求换成FormBody 封装键值对参数

FormBody.Builder builder = new FormBody.Builder();
//遍历集合
for (String key : params.keySet()) {
builder.add(key, params.get(key));
}

//创建Request
Request request = new Request.Builder().url(url).post(builder.build()).build();

Call call = okHttpClient.newCall(request);
call.enqueue(callback);
}
/**
* post请求上传文件....包括图片....流的形式传任意文件...
* 参数1 url
* file表示上传的文件
* fileName....文件的名字,,例如aaa.jpg
* params ....传递除了file文件 其他的参数放到map集合
*/
public static void uploadFile(String url, File file, String fileName,Map<String,String> params) {
//创建OkHttpClient请求对象
OkHttpClient okHttpClient = getInstance();

MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);

//参数
if (params != null){
for (String key : params.keySet()){
builder.addFormDataPart(key,params.get(key));
}
}
//文件...参数name指的是请求路径中所接受的参数...如果路径接收参数键值是fileeeee,此处应该改变
builder.addFormDataPart("file",fileName, RequestBody.create(MediaType.parse("application/octet-stream"),file));

//构建
MultipartBody multipartBody = builder.build();

//创建Request
Request request = new Request.Builder().url(url).post(multipartBody).build();

//得到Call
Call call = okHttpClient.newCall(request);
//执行请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {

}

@Override
public void onResponse(Call call, Response response) throws IOException {
//上传成功回调 目前不需要处理
if (response.isSuccessful()){
String s = response.body().string();
}
}
});
}

/**
* Post请求发送JSON数据....{"name":"zhangsan","pwd":"123456"}
* 参数一:请求Url
* 参数二:请求的JSON
* 参数三:请求回调
*/
public static void doPostJson(String url, String jsonParams, Callback callback) {
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);
Request request = new Request.Builder().url(url).post(requestBody).build();
Call call = getInstance().newCall(request);
call.enqueue(callback);
}

/**
* 下载文件 以流的形式把apk写入的指定文件 得到file后进行安装
* 参数er:请求Url
* 参数san:保存文件的文件夹....download
*/
public static void download(final Activity context, final String url, final String saveDir) {
Request request = new Request.Builder().url(url).build();
Call call = getInstance().newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}

@Override
public void onResponse(Call call, final Response response) throws IOException {

InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
is = response.body().byteStream();//以字节流的形式拿回响应实体内容
//apk保存路径
final String fileDir = isExistDir(saveDir);
//文件
File file = new File(fileDir, getNameFromUrl(url));

fos = new FileOutputStream(file);
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
fos.flush();

context.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "下载成功:" + fileDir + "," + getNameFromUrl(url), Toast.LENGTH_SHORT).show();
}
});

//apk下载完成后 调用系统的安装方法
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
context.startActivity(intent);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) is.close();
if (fos != null) fos.close();
}
}
});
}
private static String isExistDir(String saveDir) throws IOException {
// 下载位置
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
if (!downloadFile.mkdirs()) {
downloadFile.createNewFile();
}
String savePath = downloadFile.getAbsolutePath();
Log.e("savePath", savePath);
return savePath;
}
return null;
}
/**
* @param url
* @return 从下载连接中解析出文件名
*/
private static String getNameFromUrl(String url) {
return url.substring(url.lastIndexOf("/") + 1);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐