//添加依赖,涉及到json解析,图片加载,ok请求,recyclerview
compile 'com.squareup.okhttp3:okhttp:3.6.0'
compile 'com.squareup.okio:okio:1.11.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.youth.banner:banner:1.4.9'
compile 'com.orhanobut:logger:2.1.1'
compile 'com.google.code.gson:gson:2.8.2'
compile 'com.android.support:recyclerview-v7:25.3.1'
//util工具类
public class ApiUtil {
public static final String LOGIN_URL = "https://www.zhaoapi.cn/user/login";
public static final String REGIST_URL = "https://www.zhaoapi.cn/user/reg";
public static final String SEARCH_URL = "http://120.27.23.105/product/searchProducts";
}
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class OkHttp3Util {
/**
* 懒汉 安全 加同步
* 私有的静态成员变量 只声明不创建
* 私有的构造方法
* 提供返回实例的静态方法
*/
private static OkHttpClient okHttpClient = null;
private OkHttp3Util() {
}
public static OkHttpClient getInstance() {
if (okHttpClient == null) {
//加同步安全
synchronized (OkHttp3Util.class) {
if (okHttpClient == null) {
//okhttp可以缓存数据....指定缓存路径
File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");
//指定缓存大小
int cacheSize = 10 * 1024 * 1024;
okHttpClient = new OkHttpClient.Builder()//构建器
.connectTimeout(15, TimeUnit.SECONDS)//连接超时
.writeTimeout(20, TimeUnit.SECONDS)//写入超时
.readTimeout(20, TimeUnit.SECONDS)//读取超时
.cache(new Cache(sdcache.getAbsoluteFile(), cacheSize))//设置缓存
.build();
}
}
}
return okHttpClient;
}
/**
* get请求
* 参数1 url
* 参数2 回调Callback
*/
public static void doGet(String url, Callback callback) {
//创建OkHttpClient请求对象
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 params post请求的时候给服务器传的数据
* add..("","")
* add()
*/
public static void doPost(String url, Map 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 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();
com.orhanobut.logger.Logger.e("上传--"+s);
}
}
});
}
/**
* 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) {
com.orhanobut.logger.Logger.e(e.getLocalizedMessage());
}
@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();
}
}
});
}
/**
* 判断下载目录是否存在......并返回绝对路径
*
* @param saveDir
* @return
* @throws IOException
*/
public 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);
}
}
import android.content.Context;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.youth.banner.loader.ImageLoader;
public class GlideImageLoader extends ImageLoader {
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
Glide.with(context).load(path).into(imageView);
}
}
//MVP模式 m层
import android.util.Log;
import com.cuijiajum.sanzhou.bean.AllContent;
import com.cuijiajum.sanzhou.persenter.IPresenterSearch;
import com.cuijiajum.sanzhou.util.OkHttp3Util;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class SearchModel {
private IPresenterSearch iPresenterSearch;
public SearchModel(IPresenterSearch iPresenterSearch) {
this.iPresenterSearch = iPresenterSearch;
}
public void getData(String loginUrl, String keywords) {
Map map = new HashMap<>();
Log.d("++++++++++++++",loginUrl);
map.put("keywords",keywords);
map.put("page","1");
map.put("source","android");
OkHttp3Util.doGet(loginUrl+"?keywords="+keywords+"&page="+1+"&source="+"android", 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 json = response.body().string();
if(json!=null){
//使用原生解析
try {
Gson gson = new Gson();
AllContent allContent = gson.fromJson(json, AllContent.class);
//使用接口回调
iPresenterSearch.onSuccess(allContent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
});
}
}
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.cuijiajum.sanzhou.Liushi;
import com.cuijiajum.sanzhou.R;
import com..cuijiajum.sanzhou.shujuku.Dao;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Liushi mFlowLayout;
private EditText name;
private Dao dao;
private ListView lv;
private ArrayAdapter adapter;
private List sel;
private Button btn;
List a=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFlowLayout = findViewById(R.id.ls);
name = findViewById(R.id.name);
lv = findViewById(R.id.lv);
btn = findViewById(R.id.btn);
dao = new Dao(MainActivity.this);
sel = dao.sel();
adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, sel);
lv.setAdapter(adapter);
zhanshi();
initChildViews();
}
private void zhanshi() {
List sel4 = dao.sel();
ArrayAdapter ada = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, sel4);
lv.setAdapter(ada);
}
private String mNames[] = {
"内衣","外套","裤衩",
"男鞋","女鞋","text",
"name","type","search","logcat",
"耐克","阿迪达斯","李宁",
"361度","女鞋"
};
private void initChildViews() {
ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.leftMargin = 10;
lp.rightMargin = 10;
lp.topMargin = 5;
lp.bottomMargin = 5;
for (int i = 0; i < mNames.length; i++) {
TextView view = new TextView(this);
view.setText(mNames[i]);
view.setTextColor(Color.WHITE);
final int finalI = i;
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,mNames[finalI], Toast.LENGTH_SHORT).show();
}
});
view.setBackgroundDrawable(getResources().getDrawable(R.drawable.textview_bg));
mFlowLayout.addView(view, lp);
}
}
public void delall(View view) {
dao.del();
List sel2 = dao.sel();
ArrayAdapter adapter2 = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, sel2);
lv.setAdapter(adapter2);
Toast.makeText(MainActivity.this,"清除成功",Toast.LENGTH_LONG).show();
btn.setVisibility(View.INVISIBLE);
}
public void add(View view) {
String n = name.getText().toString();
int i = dao.insertJson(n);
btn.setVisibility(View.VISIBLE);
List sel3 = dao.sel();
a.add(0,n);
ArrayAdapter adapter3 = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, a);
Intent intent = new Intent(MainActivity.this,SearchActivity.class);
intent.putExtra("name",n);
startActivity(intent);
lv.setAdapter(adapter3);
}
}
package com.cuijiajum.sanzhou.View;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.cuijiajum.sanzhou.R;
import com.cuijiajum.sanzhou.adapter.OnItemClickListner;
import com.cuijiajum.sanzhou.adapter.SearchRecyclerAdapter;
import com.cuijiajum.sanzhou.adapter.SearchRecyclerGVAdapter;
import com.cuijiajum.sanzhou.bean.AllContent;
import com.cuijiajum.sanzhou.persenter.SearchPresenter;
import com.cuijiajum.sanzhou.util.ApiUtil;
import com.gson.Gson;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
public class SearchActivity extends AppCompatActivity implements IViewSearch, OnItemClickListner {
private RecyclerView recycler_view;
private SearchPresenter searchPresenter;
private CheckBox ck;
boolean flag = false;
private String keywords;
private String name;
private List data;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Intent intent = getIntent();
name = intent.getStringExtra("name");
recycler_view = findViewById(R.id.recycler_view);
ck = findViewById(R.id.ck);
searchPresenter = new SearchPresenter(this);
try {
keywords = URLEncoder.encode(name, "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
searchPresenter.getData(ApiUtil.SEARCH_URL,keywords);
}
@Override
public void onSuccess(final AllContent allContent) {
runOnUiThread(new Runnable() {
@Override
public void run() {
data = allContent.getData();
Toast.makeText(SearchActivity.this, allContent.getMsg(),Toast.LENGTH_SHORT).show();
//设置适配器
/*SearchRecyclerAdapter adapter = new SearchRecyclerAdapter(SearchActivity.this,data);
recycler_view.setAdapter(adapter);
recycler_view.setLayoutManager(new LinearLayoutManager(SearchActivity.this, LinearLayout.VERTICAL,false));*/
setAdapter(data);
ck.setChecked(flag);
ck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag){
//设置管理器、适配器
setAdapter(data);
ck.setChecked(false);
flag = ck.isChecked();
}else{
SearchRecyclerGVAdapter gvAdapter = new SearchRecyclerGVAdapter(SearchActivity.this, data);
recycler_view.setAdapter(gvAdapter);
recycler_view.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
gvAdapter.setOnitemClickListner(new OnItemClickListner() {
@Override
public void onItemClick(int position) {
Intent intent = new Intent(SearchActivity.this, GoodsActivity.class);
intent.putExtra("pid",data.get(0).getPid());
startActivity(intent);
}
@Override
public void onItemLongClickListner(int position) {
}
});
ck.setChecked(true);
flag = ck.isChecked();
}
}
});
}
});
}
private void setAdapter(List data) {
SearchRecyclerAdapter adapter = new SearchRecyclerAdapter(SearchActivity.this,data);
recycler_view.setAdapter(adapter);
recycler_view.setLayoutManager(new LinearLayoutManager(SearchActivity.this, LinearLayout.VERTICAL,false));
adapter.setOnitemClickListner(this);
}
@Override
public void onItemClick(int position) {
Intent intent = new Intent(SearchActivity.this, GoodsActivity.class);
intent.putExtra("pid",data.get(0).getPid());
startActivity(intent);
}
@Override
public void onItemLongClickListner(int position) {
}
}
/**
* Created by 李欣 on 2017/12/9.
*/
public interface IViewSearch {
void onSuccess(AllContent allContent);
}
import android.content.Intent;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.cuijiajum.sanzhou.R;
import com.cuijiajum.sanzhou.bean.GoodsBean;
import com.cuijiajum.sanzhou.util.GlideImageLoader;
import com.cuijiajum.sanzhou.util.OkHttp3Util;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class GoodsActivity extends AppCompatActivity {
private int pid;
private Banner mbanner;
private TextView title_01,price_01,price_02;
private List img = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_goods);
Intent intent = getIntent();
pid = intent.getIntExtra("pid", 0);
mbanner = findViewById(R.id.mbanner);
title_01 = findViewById(R.id.title_goods);
price_01 = findViewById(R.id.price_01_goods);
price_02 = findViewById(R.id.price_02_goods);
price_01.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
OkHttp3Util.doGet("https://www.zhaoapi.cn/product/getProductDetail?pid="+pid+"&source=android", new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(response.isSuccessful()){
String json = response.body().string();
Gson gson = new Gson();
GoodsBean goodsBean = gson.fromJson(json, GoodsBean.class);
String images = goodsBean.getData().getImages();
final double bargainPrice = goodsBean.getData().getBargainPrice();
final double price = goodsBean.getData().getPrice();
final String title = goodsBean.getData().getTitle();
String[] split = images.split("\\|");
for (String str :split){
img.add(str);
}
runOnUiThread(new Runnable() {
@Override
public void run() {
//设置图片加载器
mbanner.setImageLoader(new GlideImageLoader());
//设置图片集合
mbanner.setImages(img);
//设置自动轮播,默认为true
mbanner.isAutoPlay(false);
//设置轮播时间
mbanner.setDelayTime(1500);
//banner设置方法全部调用完毕时最后调用
mbanner.start();
title_01.setText(title);
price_01.setText("原价:¥"+price+"");
price_02.setText("优惠价:¥"+bargainPrice+"");
}
});
}
}
});
}
public void add_gouwuche(View view) {
OkHttp3Util.doGet("https://www.zhaoapi.cn/product/addCart?pid=" + pid + "&uid=2809&source=android", new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String string = response.body().string();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(GoodsActivity.this,"添加成功",Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
}
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Myhelpher extends SQLiteOpenHelper {
public Myhelpher(Context context) {
super(context,"sss.db",null, 2);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//创建表
sqLiteDatabase.execSQL("create table shuju1(id integer primary key autoincrement,json text not null)");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
public class Dao {
private Myhelpher my;
private SQLiteDatabase db;
private SQLiteDatabase d;
public Dao(Context context) {
my= new Myhelpher(context);
}
/**
* 插入数据的操作
*/
public int insertJson(String json){
SQLiteDatabase database = my.getWritableDatabase();
//再去添加
ContentValues values = new ContentValues();
values.put("json",json);
database.insert("shuju1",null,values);
//关闭
database.close();
return 1;
}
public List sel(){
d = my.getReadableDatabase();
List list=new ArrayList<>();
Cursor cursor = d.rawQuery("select * from shuju1", null);
while (cursor.moveToNext()){
String s = cursor.getString(1);
list.add(s);
}
return list;
}
public void del(){
db = my.getWritableDatabase();
db.execSQL("delete from shuju1");
}
public int delyi(String i){
db = my.getWritableDatabase();
db.execSQL("delete from shuju1 where json=?",new String[]{i});
return 1;
}
}
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
/**
* Created by hasee on 2017/12/16.
*/
public class Liushi extends ViewGroup {
//存储所有子View
private List> mAllChildViews = new ArrayList<>();
//每一行的高度
private List mLineHeight = new ArrayList<>();
public Liushi(Context context) {
super(context);
}
public Liushi(Context context, AttributeSet attrs) {
super(context, attrs);
}
public Liushi(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, 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 b, int l, int i1, int i2, int i3) {
mAllChildViews.clear();
mLineHeight.clear();
//获取当前ViewGroup的宽度
int width = getWidth();
int lineWidth = 0;
int lineHeight = 0;
//记录当前行的view
List lineViews = new ArrayList();
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;
}
}
/**
159. * 与当前ViewGroup对应的LayoutParams
160. */
@Override
public LayoutParams generateLayoutParams(AttributeSet attrs) {
// TODO Auto-generated method stub
return new MarginLayoutParams(getContext(), attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
}
return true;
}
}
public interface IPresenterSearch {
void onSuccess(AllContent allContent);
}
import com.cuijiajum.sanzhou.View.IViewSearch;
import com.cuijiajum.sanzhou.View.SearchActivity;
import com.cuijiajum.sanzhou.bean.AllContent;
import com.cuijiajum.sanzhou.model.SearchModel;
public class SearchPresenter implements IPresenterSearch{
SearchModel searchModel = new SearchModel(this);
private IViewSearch iViewSearch;
public SearchPresenter(SearchActivity iViewSearch) {
this.iViewSearch = iViewSearch;
}
public void getData(String searchUrl, String keywords) {
searchModel.getData(searchUrl,keywords);
}
@Override
public void onSuccess(AllContent allContent) {
iViewSearch.onSuccess(allContent);
}
}
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class SearchRecyclerHolder extends RecyclerView.ViewHolder {
public ImageView img;
public TextView title;
public TextView price;
public SearchRecyclerHolder(View itemView) {
super(itemView);
img = (ImageView) itemView.findViewById(R.id.img);
price = (TextView) itemView.findViewById(R.id.price);
title = (TextView) itemView.findViewById(R.id.title);
}
}
public interface OnItemClickListner {
public void onItemClick(int position);
public void onItemLongClickListner(int position);
}
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.cuijiajum.sanzhou.R;
import com.cuijiajum.sanzhou.bean.AllContent;
import com.cuijiajum.sanzhou.holder.SearchRecyclerHolder;
import com.bumptech.glide.Glide;
import java.util.List;
public class SearchRecyclerAdapter extends RecyclerView.Adapter {
Context context;
List data;
private OnItemClickListner onItemClickListner;
public SearchRecyclerAdapter(Context context, List data) {
this.context = context;
this.data = data;
}
@Override
public SearchRecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
SearchRecyclerHolder searchRecyclerHolder = new SearchRecyclerHolder(view);
return searchRecyclerHolder;
}
@Override
public void onBindViewHolder(SearchRecyclerHolder holder, final int position) {
AllContent.DataBean dataBean = data.get(position);
String images = dataBean.getImages();
String[] split = images.split("\\|");
//设置数据
Glide.with(context).load(split[0]).into(holder.img);
holder.price.setText("¥"+dataBean.getPrice()+"");
holder.title.setText(dataBean.getTitle());
holder.title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onItemClickListner.onItemClick(position);
}
});
}
@Override
public int getItemCount() {
return data.size();
}
public void setOnitemClickListner(OnItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
//onItemClickListner.onItemClick();
}
}
package com.cuijiajum.sanzhou.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.cuijiajum.sanzhou.R;
import com.cuijiajum.sanzhou.bean.AllContent;
import com.cuijiajum.sanzhou.holder.SearchRecyclerHolder;
import com.bumptech.glide.Glide;
import java.util.List;
public class SearchRecyclerGVAdapter extends RecyclerView.Adapter {
Context context;
List data;
private OnItemClickListner onItemClickListner;
public SearchRecyclerGVAdapter(Context context, List data) {
this.context = context;
this.data = data;
}
@Override
public SearchRecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.grid_item, parent, false);
SearchRecyclerHolder searchRecyclerHolder = new SearchRecyclerHolder(view);
return searchRecyclerHolder;
}
@Override
public void onBindViewHolder(SearchRecyclerHolder holder, final int position) {
AllContent.DataBean dataBean = data.get(position);
String images = dataBean.getImages();
String[] split = images.split("\\|");
//设置数据
Glide.with(context).load(split[0]).into(holder.img);
holder.price.setText("¥"+dataBean.getPrice()+"");
holder.title.setText(dataBean.getTitle());
holder.title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onItemClickListner.onItemClick(position);
}
});
}
@Override
public int getItemCount() {
return data.size();
}
public void setOnitemClickListner(OnItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
//onItemClickListner.onItemClick();
}
}
//main布局
//search页面
//goods商品详情界面
//适配器需要加载的界面
//条目布局
//适配器表格布局