所需依赖
/*banner轮播图 依赖*/
implementation 'com.youth.banner:banner:1.4.9'
/*gson解析*/
implementation 'com.google.code.gson:gson:2.2.4'
/*okhttp网络请求*/
implementation 'com.squareup.okhttp3:okhttp:3.12.0'
/*recyclerview展示*/
implementation 'com.android.support:recyclerview-v7:28.0.0'
/*xrecyclerview展示*/
implementation 'com.jcodecraeer:xrecyclerview:1.2.0'
/*glide图片工具*/
implementation 'com.github.bumptech.glide:glide:4.8.0'
IVew
public interface IView {
public Context context();
}
DataCall–继承IVew
public interface DataCall extends IView {
void ShowSuccess(GoodsBean goodsBean);
void ShowError(String error);
}
Model
public class GoodsModel {
public void showGoods(int page, String name, final MainmodelCallback mainmodelCallback) {
HttpUtils httpUtils = HttpUtils.getHttpUtils();
String url = "http://www.zhaoapi.cn/product/searchProducts?keywords=" + name + "&page=" + page;
httpUtils.doGet(url, new HttpUtils.IOKhttpUtilsCallback() {
@Override
public void onFailure(String error) {
if (mainmodelCallback != null) {
mainmodelCallback.getFaid(error);
}
}
@Override
public void onResponse(String json) {
GoodsBean goodsBean = new Gson().fromJson(json, GoodsBean.class);
if (goodsBean.getCode().equals("0")) {
if (mainmodelCallback != null) {
mainmodelCallback.getSuccess(goodsBean);
}
} else {
if (mainmodelCallback != null) {
mainmodelCallback.getFaid("请求失败");
}
}
}
});
}
public interface MainmodelCallback {
void getSuccess(GoodsBean goodsBean);
void getFaid(String error);
}
}
HttpUtils
public class HttpUtils {
public static HttpUtils httpUtils;
private final Handler handler;
private final OkHttpClient HttpClient;
private HttpUtils() {
//主线程Handler
handler = new Handler(Looper.getMainLooper());
HttpClient = new OkHttpClient.Builder()
.readTimeout(5000, TimeUnit.MILLISECONDS)
.writeTimeout(5000, TimeUnit.MILLISECONDS)
.connectTimeout(5000, TimeUnit.MILLISECONDS)
.connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))//内存溢出
.build();
}
public static HttpUtils getHttpUtils() {
if (httpUtils == null) {
synchronized (HttpUtils.class) {
if (httpUtils == null) {
return httpUtils = new HttpUtils();
}
}
}
return httpUtils;
}
//异步get
public void doGet(String url, final IOKhttpUtilsCallback ioKhttpUtilsCallback) {
Request request = new Request.Builder().get().url(url).build();
Call call = HttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
if (ioKhttpUtilsCallback != null) {
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onFailure(e.getMessage());
}
});
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()) {
final String json = response.body().string();
if (ioKhttpUtilsCallback != null) {
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onResponse(json);
}
});
}
} else {
if (ioKhttpUtilsCallback != null) {
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onFailure("网络异常");
}
});
}
}
}
});
}
//异步post
public void doPost(String url, Map<String, String> map, final IOKhttpUtilsCallback ioKhttpUtilsCallback) {
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String, String> entry : map.entrySet()) {
builder.add(entry.getKey(), entry.getValue());
}
FormBody formBody = builder.build();
Request request = new Request.Builder()
.post(formBody)
.url(url)
.build();
Call call = HttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
if (ioKhttpUtilsCallback != null) {
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onFailure(e.getMessage());
}
});
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response != null && response.isSuccessful()) {
final String json = response.body().string();
if (ioKhttpUtilsCallback != null) {
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onResponse(json);
}
});
}
} else {
if (ioKhttpUtilsCallback != null) {
//切换到主线程
handler.post(new Runnable() {
@Override
public void run() {
ioKhttpUtilsCallback.onFailure("网络异常");
}
});
}
}
}
});
}
//接口回调
public interface IOKhttpUtilsCallback {
void onFailure(String error);
void onResponse(String json);
}
}
BasePresenter
public abstract class BasePresenter<V extends IView> {
protected V view;
public BasePresenter(V view) {
this.view = view;
initModel();
}
protected abstract void initModel();
public void onDestroy() {
view = null;
}
}
Presenter
public class GoodsPresenter extends BasePresenter<DataCall> {
private GoodsModel goodsModel;
public GoodsPresenter(DataCall view) {
super(view);
}
@Override
protected void initModel() {
goodsModel = new GoodsModel();
}
public void showGoods(int page, String name) {
goodsModel.showGoods(page, name, new GoodsModel.MainmodelCallback() {
@Override
public void getSuccess(GoodsBean goodsBean) {
view.ShowSuccess(goodsBean);
}
@Override
public void getFaid(String error) {
view.ShowError(error);
}
});
}
}
Activity
public class MainActivity extends AppCompatActivity implements View.OnClickListener, DataCall {
private ImageView mBtnBack;
private ImageView mBtnMenu;
private XRecyclerView mXrecy;
private int type = 1;
private GoodsAdapter adapter;
private SearchView mSea;
private GoodsPresenter presenter;
private List<GoodsBean.DataBean> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
initView();
//数据获取
initData();
//刷新加载
initRefresh();
mSea = (SearchView) findViewById(R.id.sea);
mSea.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
presenter.showGoods(1, s);
return false;
}
});
}
private void initRefresh() {
mXrecy.setLoadingListener(new XRecyclerView.LoadingListener() {
@Override
public void onRefresh() {
//更新UI
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mXrecy.refreshComplete();
Toast.makeText(MainActivity.this, "刷新完成", Toast.LENGTH_SHORT).show();
}
}, 2000);
}
@Override
public void onLoadMore() {
//更新UI
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mXrecy.loadMoreComplete();
Toast.makeText(MainActivity.this, "加载完成", Toast.LENGTH_SHORT).show();
}
}, 2000);
}
});
}
private void initData() {
presenter = new GoodsPresenter(this);
presenter.showGoods(1, "笔记本");
mBtnMenu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (type == 1) {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mXrecy.setLayoutManager(linearLayoutManager);
adapter.notifyDataSetChanged();
type = 2;
} else {
GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this, 2);
mXrecy.setLayoutManager(gridLayoutManager);
adapter.notifyDataSetChanged();
type = 1;
}
}
});
}
private void initView() {
mBtnBack = (ImageView) findViewById(R.id.btn_back);
mBtnMenu = (ImageView) findViewById(R.id.btn_menu);
mBtnMenu.setOnClickListener(this);
mXrecy = (XRecyclerView) findViewById(R.id.xrecy);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
default:
break;
case R.id.btn_menu:
break;
}
}
@Override
public void ShowSuccess(GoodsBean goodsBean) {
Toast.makeText(this, "成功——————" + goodsBean.getData(), Toast.LENGTH_SHORT).show();
list = goodsBean.getData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mXrecy.setLayoutManager(linearLayoutManager);
adapter = new GoodsAdapter(list, context());
mXrecy.setAdapter(adapter);
adapter.setOnItemLongClickListener(new GoodsAdapter.OnItemLongClickListener() {
@Override
public void OnItemLongClick(View view, int position) {
ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f, 1f);
alpha.setDuration(5000);
alpha.start();
AlertDialog.Builder builder = new AlertDialog.Builder(context());
builder.setTitle("删除");
builder.setMessage("确认删除吗");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
list.remove(i);
adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("取消", null);
builder.show();
}
});
}
@Override
public void ShowError(String error) {
Toast.makeText(this, "失败——————" + error, Toast.LENGTH_SHORT).show();
}
@Override
public Context context() {
return this;
}
@Override
protected void onDestroy() {
super.onDestroy();
presenter.onDestroy();
}
}
Adapter
public class GoodsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<GoodsBean.DataBean> list;
private Context context;
public GoodsAdapter(List<GoodsBean.DataBean> list, Context context) {
this.list = list;
this.context = context;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemlayout, viewGroup, false);
return (new ViewHolder(view));
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int position) {
((ViewHolder) viewHolder).item_dec.setText(list.get(position).getTitle());
((ViewHolder) viewHolder).item_price.setText(list.get(position).getPrice() + "");
String images = list.get(position).getImages();
String imageurl = "http" + images.substring(5);
String[] split = imageurl.split("\\|");
if (split.length > 0) {
Glide.with(context).load(split[0]).into(((ViewHolder) viewHolder).item_img);
// Glide.with(context).load(ii).into(((ViewHolder) viewHolder).item_img);
}
viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
ObjectAnimator alpha = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f, 1f);
alpha.setDuration(5000);
alpha.start();
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("删除");
builder.setMessage("确认删除吗");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
list.remove(position);
notifyDataSetChanged();
}
});
builder.setNegativeButton("取消", null);
builder.show();
return true;
}
});
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(context, DataActivity.class);
intent.putExtra("aaa", list.get(position).getTitle());
intent.putExtra("bbb", list.get(position).getBargainPrice());
intent.putExtra("ccc", list.get(position).getCreatetime());
intent.putExtra("eee", list.get(position).getImages());
context.startActivity(intent);
Toast.makeText(context, "点击了" + position, Toast.LENGTH_LONG).show();
}
});
}
@Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView item_dec, item_price;
private ImageView item_img;
public ViewHolder(View itemView) {
super(itemView);
item_img = itemView.findViewById(R.id.img_icon);
item_dec = itemView.findViewById(R.id.txt_name);
item_price = itemView.findViewById(R.id.txt_price);
}
}
private OnItemLongClickListener onItemLongClickListener;
public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
this.onItemLongClickListener = onItemLongClickListener;
}
public interface OnItemLongClickListener {
void OnItemLongClick(View view, int position);
}
}
布局****
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/img_icon"
android:layout_width="120dp"
android:layout_height="120dp" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="120dp">
<TextView
android:id="@+id/txt_name"
android:text="详情"
android:textSize="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/txt_price"
android:text="价格"
android:textSize="25dp"
android:textColor="#f00"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>