接口:
public interface Api {
@GET("product/getCarts?uid=22535")
Observable<ShoppingBean> getCart();
@GET("user/getUserInfo?uid=22535&token=BC254F7FC28567CDA7AB37C837057888")
Observable<User> getUser();
@Multipart
@POST("file/upload?uid=22535&token=BC254F7FC28567CDA7AB37C837057888")
Observable<IconUpload> iconUpload(@Part MultipartBody.Part part);
}
头像上传的bean:
private String headPath;
private String message;
private String status;
public class Contant {
public static final String BASE_URL = "http://www.zhaoapi.cn/";
}
HttpUtils封装:
public class HttpUtils {
public final Api api;
public HttpUtils() {
OkHttpClient httpClient = new OkHttpClient.Builder()
.addNetworkInterceptor(new LoggingInterceptor())
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Contant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClient)
.build();
api = retrofit.create(Api.class);
}
class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long time = System.nanoTime();
Response response = chain.proceed(request);
long time1 = System.nanoTime();
return response;
}
}
private static class GETHttpUtilsinfo{
private static HttpUtils httpUtils = new HttpUtils();
}
public static HttpUtils getHttpUtilsimg(){
return GETHttpUtilsinfo.httpUtils;
}
}
p层和model层比较简单就不传了;
baseP层:
public class BasePresenter<V extends IView> {
private V v;
public void attacthView(V v){
this.v = v;
}
public void getData(){
this.v = null;
}
public V getView(){
return v;
}
}
购物车:
购物车bean里加的:
里层适配器和外层适配器都加:
private boolean isCheck;
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean check) {
isCheck = check;
}
public DataBean(boolean isCheck) {
this.isCheck = isCheck;
}
里层适配器:
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
private Context context;
private List<ShoppingBean.DataBean.ListBean> list;
public ProductAdapter(Context context, List<ShoppingBean.DataBean.ListBean> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = View.inflate(context, R.layout.item_product, null);
ViewHolder holder = new ViewHolder(v);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
final ShoppingBean.DataBean.ListBean listBean = list.get(position);
String[] split = list.get(position).getImages().replace("https", "http").split("\\|");
holder.imgProduct.setImageURI(Uri.parse(split[0]));
holder.txtProductName.setText(list.get(position).getTitle());
holder.txtSinglePriice.setText(list.get(position).getPrice()+"");
holder.cbProduct.setOnCheckedChangeListener(null);
holder.cbProduct.setChecked(listBean.isCheck());
holder.cbProduct.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listBean.setCheck(isChecked);
onProductClick.onProductClick(position, isChecked);
}
});
}
@Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private CheckBox cbProduct;
private SimpleDraweeView imgProduct;
private TextView txtProductName;
private TextView txtSinglePriice;
public ViewHolder(View itemView) {
super(itemView);
cbProduct = itemView.findViewById(R.id.cb_product);
imgProduct = itemView.findViewById(R.id.img_product);
txtSinglePriice = itemView.findViewById(R.id.txt_single_price);
txtProductName = itemView.findViewById(R.id.txt_product_name);
}
}
public interface onProductClick {
void onProductClick(int position, boolean isCheck);
}
private onProductClick onProductClick;
public void setOnProductClick(onProductClick onProductClick) {
this.onProductClick = onProductClick;
}
}
外层适配器:
public class ShopAdapter extends RecyclerView.Adapter<ShopAdapter.ViewHolder> {
private Context context;
private List<ShoppingBean.DataBean> dataBeans;
public ShopAdapter(Context context, List<ShoppingBean.DataBean> dataBeans) {
this.context = context;
this.dataBeans = dataBeans;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = View.inflate(context, R.layout.item_cart, null);
ViewHolder holder = new ViewHolder(v);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, final int position) {
final ShoppingBean.DataBean dataBean = dataBeans.get(position);
holder.txtShopperName.setText(dataBeans.get(position).getSellerName());
RecyclerView.LayoutManager pLayoutManager = new LinearLayoutManager(context);
holder.rvProduct.setLayoutManager(pLayoutManager);
final ProductAdapter adapter = new ProductAdapter(context, dataBeans.get(position).getList());
holder.rvProduct.setAdapter(adapter);
adapter.setOnProductClick(new ProductAdapter.onProductClick() {
@Override
public void onProductClick(int position, boolean isCheck) {
if (!isCheck) {
dataBean.setCheck(false);
onShopClick.onShopClick(position, false);
} else {
boolean isAll = true;
for (ShoppingBean.DataBean.ListBean listBean : dataBean.getList()) {
if (!listBean.isCheck()) {
isAll = false;
break;
}
}
dataBean.setCheck(isAll);
onShopClick.onShopClick(position, true);
}
notifyDataSetChanged();
}
});
holder.cbSHopper.setOnCheckedChangeListener(null);
holder.cbSHopper.setChecked(dataBean.isCheck());
holder.cbSHopper.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
dataBean.setCheck(isChecked);
List<ShoppingBean.DataBean.ListBean> list = dataBean.getList();
for (ShoppingBean.DataBean.ListBean listBean : list) {
listBean.setCheck(isChecked);
}
adapter.notifyDataSetChanged();
onShopClick.onShopClick(position, isChecked);
}
});
}
@Override
public int getItemCount() {
return dataBeans.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
private CheckBox cbSHopper;
private TextView txtShopperName;
private RecyclerView rvProduct;
public ViewHolder(View itemView) {
super(itemView);
cbSHopper = itemView.findViewById(R.id.cb_shopper);
txtShopperName = itemView.findViewById(R.id.txt_shopper_name);
rvProduct = itemView.findViewById(R.id.rv_product);
}
}
public interface onShopClick{
void onShopClick(int position, boolean isCheck);
}
private onShopClick onShopClick;
public void setOnShopClick(onShopClick onShopClick) {
this.onShopClick = onShopClick;
}
}
主线程:
public class ShopFragment extends Fragment implements ShoppingView {
@BindView(R.id.txt_edit_or_finish)
TextView txtEditOrFinish;
@BindView(R.id.rl_title)
RelativeLayout rlTitle;
@BindView(R.id.cb_total_select)
CheckBox cbTotalSelect;
@BindView(R.id.txt_total_price)
TextView txtTotalPrice;
@BindView(R.id.btn_calu)
Button btnCalu;
@BindView(R.id.btn_del)
Button btnDel;
@BindView(R.id.rl_bottom)
RelativeLayout rlBottom;
@BindView(R.id.rv_shopper)
RecyclerView rvShopper;
Unbinder unbinder;
private ShoppingPresenter presenter;
private List<ShoppingBean.DataBean> dataBeans;
private ShopAdapter shopAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_shop, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dataBeans = new ArrayList<>();
shopAdapter = new ShopAdapter(getActivity(),dataBeans);
presenter = new ShoppingPresenter();
presenter.attacthView(this);
presenter.getData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
rvShopper.setLayoutManager(linearLayoutManager);
rvShopper.setAdapter(shopAdapter);
shopAdapter.setOnShopClick(new ShopAdapter.onShopClick() {
@Override
public void onShopClick(int position, boolean isCheck) {
if (!isCheck) {
cbTotalSelect.setChecked(false);
} else {
boolean isAll = true;
for (ShoppingBean.DataBean dataBean : dataBeans) {
if (!dataBean.isCheck()) {
isAll = false;
break;
}
}
cbTotalSelect.setChecked(isAll);
}
getCount();
}
});
cbTotalSelect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
boolean checked = cbTotalSelect.isChecked();
for (ShoppingBean.DataBean dataBean : dataBeans) {
dataBean.setCheck(checked);
for (ShoppingBean.DataBean.ListBean listBean : dataBean.getList()) {
listBean.setCheck(checked);
}
}
getCount();
}
});
}
private void getCount() {
float total = 0;
for (ShoppingBean.DataBean dataBean : dataBeans) {
for (ShoppingBean.DataBean.ListBean listBean : dataBean.getList()) {
if (listBean.isCheck()) {
total += listBean.getPrice();
}
}
}
shopAdapter.notifyDataSetChanged();
txtTotalPrice.setText(total + "");
}
@Override
public void onSuccess(List<ShoppingBean.DataBean> list) {
if (list != null) {
dataBeans.clear();
dataBeans.addAll(list);
shopAdapter.notifyDataSetChanged();
}
}
@Override
public void onError() {
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
}
上传头像的主要代码:
public class MyFragment extends Fragment implements HeadView {
private ImageView mHeader_iv;
//相册请求码
private static final int ALBUM_REQUEST_CODE = 1;
//相机请求码
private static final int CAMERA_REQUEST_CODE = 2;
//剪裁请求码
private static final int CROP_REQUEST_CODE = 3;
//调用照相机返回图片文件
private File tempFile;
@BindView(R.id.sim_dra_view)
SimpleDraweeView simDraView;
Unbinder unbinder;
@BindView(R.id.text_name)
TextView textName;
private HeadPresenter presenter;
private IconUploadModelPresenter iconUploadModelPresenter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_my, container, false);
unbinder = ButterKnife.bind(this, view);
presenter = new HeadPresenter();
iconUploadModelPresenter = new IconUploadModelPresenter();
iconUploadModelPresenter.attacthView(this);
presenter.attacthView(this);
presenter.getData();
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
simDraView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder dia = new AlertDialog.Builder(getActivity());
final AlertDialog dialog = dia.create();
View view = View.inflate(getActivity(), R.layout.add_image, null);
View xiangji = view.findViewById(R.id.tv_select_camera);
View xiangce = view.findViewById(R.id.tv_select_gallery);
xiangji.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tempFile = new File(Environment.getExternalStorageDirectory().getPath(), System.currentTimeMillis() + ".jpg");
//跳转到调用系统相机
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//判断版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //如果在Android7.0以上,使用FileProvider获取Uri
intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(getActivity(), "com.hansion.chosehead", tempFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
Log.e("dasd", contentUri.toString());
} else { //否则使用Uri.fromFile(file)方法获取Uri
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
}
startActivityForResult(intent, CAMERA_REQUEST_CODE);
dialog.dismiss();
}
});
xiangce.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, ALBUM_REQUEST_CODE);
dialog.dismiss();
}
});
dialog.setView(view);
dialog.show();
}
});
}
private void cropPhoto(Uri uri) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.setDataAndType(uri, "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("return-data", true);
startActivityForResult(intent, CROP_REQUEST_CODE);
}
public String saveImage(String name, Bitmap bmp) {
File appDir = new File(Environment.getExternalStorageDirectory().getPath());
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = name + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
return file.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case CAMERA_REQUEST_CODE: //调用相机后返回
if (resultCode == RESULT_OK) {
//用相机返回的照片去调用剪裁也需要对Uri进行处理
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri contentUri = FileProvider.getUriForFile(getActivity(), "com.hansion.chosehead", tempFile);
cropPhoto(contentUri);
} else {
cropPhoto(Uri.fromFile(tempFile));
}
}
break;
case ALBUM_REQUEST_CODE: //调用相册后返回
if (resultCode == RESULT_OK) {
Uri uri = intent.getData();
cropPhoto(uri);
}
break;
case CROP_REQUEST_CODE: //调用剪裁后返回
Bundle bundle = intent.getExtras();
if (bundle != null) {
//在这里获得了剪裁后的Bitmap对象,可以用于上传
Bitmap image = bundle.getParcelable("data");
//设置到ImageView上
simDraView.setImageBitmap(image);
//也可以进行一些保存、压缩等操作后上传
String path = saveImage("crop", image);
File file = new File(path);
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
iconUploadModelPresenter.getData(part);
}
break;
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@Override
public void onSuccess(User.DataBean list) {
Uri parse = Uri.parse(list.getIcon().replace("https", "http"));
simDraView.setImageURI(parse);
textName.setText(list.getMobile());
}
@Override
public void onLSuccess(IconUpload iconUpload) {
}
@Override
public void onError() {
}
@Override
public void onLError() {
}
}