仿京東 --- 首頁
阿新 • • 發佈:2018-12-11
前邊有介面滑動和底部導航欄,這個比較簡單就不做了。
介面用到的圖示在網上找吧,這裡我就不發了。
主介面佈局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.bw.movie.diyview.MyScrollView android:id="@+id/index_sv" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <com.youth.banner.Banner android:id="@+id/index_banner" android:layout_width="match_parent" android:layout_height="200dp"></com.youth.banner.Banner> <android.support.v7.widget.RecyclerView android:id="@+id/index_jgg" android:layout_width="match_parent" android:layout_height="wrap_content"></android.support.v7.widget.RecyclerView> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:layout_width="60dp" android:layout_height="20dp" android:src="@drawable/kaui" /> <ViewFlipper android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:autoStart="true" android:flipInterval="3000" android:inAnimation="@anim/anim_in" android:outAnimation="@anim/anim_out"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxLines="1" android:text="hot vivo X20 帶你開啟全面屏時代!逆光也清晰,照亮你的美!" android:textSize="12dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxLines="1" android:text="推薦 【現貨新品搶購】全面屏2.0震撼來襲,驍龍835處理器,四曲面陶瓷機" android:textSize="12dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxLines="1" android:text="熱門 Super AMOLED三星雙曲面2K 屏,支援無線充電!" android:textSize="12dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxLines="1" android:text="最新 升級4G大視訊記憶體!Nvme協議Pcie SSD,速度快人一步】GTX1050Ti就選拯救者!" android:textSize="12dp" /> </ViewFlipper> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <ImageView android:layout_width="60dp" android:layout_height="20dp" android:src="@drawable/miaos" /> <TextView android:text="00點場" android:id="@+id/index_even" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" /> <TextView android:layout_marginLeft="15dp" android:id="@+id/index_hour" android:text="00" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text=":" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/index_minute" android:text="00" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text=":" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/index_second" android:text="00" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/tuijian" /> <android.support.v7.widget.RecyclerView android:id="@+id/index_tuijian" android:layout_width="match_parent" android:layout_height="match_parent"></android.support.v7.widget.RecyclerView> </LinearLayout> </com.bw.movie.diyview.MyScrollView> <include layout="@layout/mysearch"></include> </RelativeLayout>
標題佈局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:background="@color/white" android:id="@+id/sousuokuang" android:layout_height="50dp" android:orientation="horizontal" android:gravity="center_vertical" > <TextView android:id="@+id/mysearch_sao" android:gravity="center" android:text="掃一掃" android:layout_width="0dp" android:layout_height="30dp" android:layout_weight="2" /> <RelativeLayout android:id="@+id/mysearch_rl" android:layout_width="0dp" android:layout_height="30dp" android:layout_weight="6" android:background="@drawable/suosuo"> <ImageView android:layout_marginTop="3dp" android:layout_width="25dp" android:layout_height="25dp" android:layout_alignParentStart="true" android:layout_alignParentTop="true" android:src="@drawable/a_4" /> <ImageView android:layout_marginTop="3dp" android:layout_width="25dp" android:layout_height="25dp" android:layout_alignParentEnd="true" android:layout_alignParentTop="true" android:src="@drawable/root" /> </RelativeLayout> <TextView android:id="@+id/mysearch_info" android:gravity="center" android:text="訊息" android:layout_width="0dp" android:layout_height="30dp" android:layout_weight="2" /> </LinearLayout>
主介面程式碼 IndexFragment
public class IndexFragment extends Fragment implements IndexView { @BindView(R.id.index_banner) Banner indexBanner; Unbinder unbinder; @BindView(R.id.index_jgg) RecyclerView indexJgg; @BindView(R.id.index_tuijian) RecyclerView indexTuijian; @BindView(R.id.sousuokuang) LinearLayout sousuokuang; @BindView(R.id.index_sv) MyScrollView indexSv; @BindView(R.id.mysearch_sao) TextView mysearchSao; @BindView(R.id.mysearch_rl) RelativeLayout mysearchRl; @BindView(R.id.mysearch_info) TextView mysearchInfo; @BindView(R.id.index_even) TextView indexEven; @BindView(R.id.index_hour) TextView indexHour; @BindView(R.id.index_minute) TextView indexMinute; @BindView(R.id.index_second) TextView indexSecond; private IndexPresenter presenter; private List<Ad.DataBean> data; private List<Ad.TuijianBean.ListBean> tuijian; private CompositeDisposable compositeDisposable = new CompositeDisposable(); private final int REQUEST_CODE = 200; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = View.inflate(getActivity(), R.layout.index_fg, null); unbinder = ButterKnife.bind(this, view); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); presenter = new IndexPresenter(this); //初始化首頁資料 initData(); sousuokuang.getBackground().setAlpha(0); indexSv.setOnScrollChanged(new MyScrollView.OnScrollChanged() { @Override public void onScrollChanged(int x, int y, int oldx, int oldy) { // Log.d("aaa", x + "," + y + "=====" + oldx + "," + oldy); if (y < 270) { int i = (int) ((float) y / (float) 270 * 255); sousuokuang.getBackground().setAlpha(i); } else { sousuokuang.getBackground().setAlpha(255); } } }); } private void initData() { initMiaosha(); indexJgg.setLayoutManager(new GridLayoutManager(getActivity(), 2, LinearLayoutManager.HORIZONTAL, false)); indexTuijian.setLayoutManager(new GridLayoutManager(getActivity(), 2)); //關閉巢狀滑動 indexTuijian.setNestedScrollingEnabled(false); //固定recyclerview尺寸 indexTuijian.setHasFixedSize(true); presenter.getAd(); presenter.getCatagory(); } private void initMiaosha() { Observable.interval(1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Long>() { @Override public void onSubscribe(Disposable d) { compositeDisposable.add(d); } @Override public void onNext(Long aLong) { upDateMiaosha(); } @Override public void onError(Throwable e) { } @Override public void onComplete() { } }); } private void upDateMiaosha() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date curDate = new Date(System.currentTimeMillis()); String format = df.format(curDate); StringBuffer buffer = new StringBuffer(); String substring = format.substring(0, 11); buffer.append(substring); Log.d("ccc", substring); Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); if (hour % 2 == 0) { indexEven.setText(hour + "點場"); buffer.append((hour + 2)); buffer.append(":00:00"); } else { indexEven.setText((hour - 1) + "點場"); buffer.append((hour + 1)); buffer.append(":00:00"); } String totime = buffer.toString(); try { Date date = df.parse(totime); Date date1 = df.parse(format); long defferenttime = date.getTime() - date1.getTime(); long days = defferenttime / (1000 * 60 * 60 * 24); long hours = (defferenttime - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60); long minute = (defferenttime - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60); long seconds = defferenttime % 60000; long second = Math.round((float) seconds / 1000); indexHour.setText("0" + hours + ""); if (minute >= 10) { indexMinute.setText(minute + ""); } else { indexMinute.setText("0" + minute + ""); } if (second >= 10) { indexSecond.setText(second + ""); } else { indexSecond.setText("0" + second + ""); } } catch (Exception e) { e.printStackTrace(); } } private void initBanner() { // List<String> title = new ArrayList<>(); List<String> path = new ArrayList<>(); for (Ad.DataBean bean : data) { path.add(bean.getIcon()); } indexBanner.setImages(path) .isAutoPlay(true) .setImageLoader(new MyLoader()) .start(); } @Override public void onDestroyView() { super.onDestroyView(); unbinder.unbind(); presenter.onDestroy(); presenter = null; } @Override public void onSuccess(Ad ad) { data = ad.getData(); tuijian = ad.getTuijian().getList(); //初始化banner initBanner(); //初始化推薦列表 initTuijian(); } private void initTuijian() { TuiJianAdapter adapter = new TuiJianAdapter(tuijian); indexTuijian.setAdapter(adapter); } @Override public void onCatagorySuccess(Catagory catagory) { List<Catagory.DataBean> data = catagory.getData(); //初始化九宮格 JggAdapter adapter = new JggAdapter(data); indexJgg.setAdapter(adapter); } @OnClick({R.id.mysearch_sao, R.id.mysearch_rl, R.id.mysearch_info}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.mysearch_sao: Intent intent = new Intent(getContext(), CaptureActivity.class); startActivityForResult(intent, REQUEST_CODE); break; case R.id.mysearch_rl: startActivity(new Intent(getContext(), QueryActivity.class)); break; case R.id.mysearch_info: break; } } @Override public void onDestroy() { super.onDestroy(); presenter = null; compositeDisposable.clear(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE) { //處理掃描結果(在介面上顯示) if (null != data) { Bundle bundle = data.getExtras(); if (bundle == null) { return; } if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) { String result = bundle.getString(CodeUtils.RESULT_STRING); Toast.makeText(getContext(), "解析結果:" + result, Toast.LENGTH_LONG).show(); } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) { Toast.makeText(getContext(), "解析二維碼失敗", Toast.LENGTH_LONG).show(); } } } } }
主介面的自定義控制元件 MyScollerView
public class MyScrollView extends ScrollView {
public MyScrollView(Context context) {
this(context,null,0);
}
public MyScrollView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public MyScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (onScrollChanged!=null){
onScrollChanged.onScrollChanged(l, t, oldl, oldt);
}
}
public interface OnScrollChanged{
void onScrollChanged(int x, int y, int oldx, int oldy);
}
private OnScrollChanged onScrollChanged;
public void setOnScrollChanged(OnScrollChanged onScrollChanged) {
this.onScrollChanged = onScrollChanged;
}
}
請求頭 Constant
public class Constant {
public static final String BASE_URL = "https://www.zhaoapi.cn/";
}
介面 Retrofit
public interface MyRetrofit {
//九宮格|分類
@GET("product/getCatagory")
Observable<Catagory> getCatagory();
//子分類
@GET("product/getProductCatagory")
Observable<ProductCatagory> getProductCatagory(@Query("cid") String cid);
//商品列表
@GET("product/getProducts")
Observable<Products> getProducts(@Query("pscid") String pscid);
//首頁
@GET("ad/getAd")
Observable<Ad> getAd();
//商品詳情
@GET("product/getProductDetail")
Observable<Detail> getDetail(@Query("pid") String pid);
//登入
@FormUrlEncoded
@POST("user/login")
Observable<Login> getLogin(@Field("mobile") String mobile, @Field("password") String password);
//註冊
@FormUrlEncoded
@POST("user/reg")
Observable<Register> getRegister(@Field("mobile") String mobile, @Field("password") String password);
//修改暱稱
@FormUrlEncoded
@POST("user/updateNickName")
Observable<UpDateNc> getUpDateNc(@Field("uid") String uid, @Field("nickname") String nickname);
//上傳頭像
@Multipart
@POST("file/upload")
Observable<UpLoadIcon> upLoadIcon(@Query("uid") String uid, @Part MultipartBody.Part part);
//查詢購物車
@FormUrlEncoded
@POST("product/getCarts")
Observable<Cart> getCart(@Field("uid") String uid);
//加入購物車
@FormUrlEncoded
@POST("product/addCart")
Observable<AddCart> getAddCart(@Field("uid") String uid, @Query("pid") String pid);
//更新購物車數量
@FormUrlEncoded
@POST("product/updateCarts")
Observable<UpdateCart> getUpdateCart(@Field("uid") String uid, @Field("sellerid") String sellerid, @Field("pid") String pid, @Field("selected") String selected, @Field("num") String num);
//刪除購物車商品
@FormUrlEncoded
@POST("product/deleteCart")
Observable<DeleteCart> deleteCart(@Field("uid") int uid, @Field("pid") int pid);
//搜尋商品
@GET("product/searchProducts")
Observable<QueryGoods> getQueryGoods(@Query("keywords") String keywords);
//建立訂單
@FormUrlEncoded
@POST("product/createOrder")
Observable<CreateOrder> getCreateOrder(@Field("uid") String uid, @Field("price") String price);
//獲得訂單列表
@GET("product/getOrders")
Observable<OrderList> getOrderList(@Query("uid") String uid, @Query("page") String page);
}
banner輪播圖的工具類 MyLoader
public class MyLoader extends ImageLoader {
@Override
public ImageView createImageView(Context context) {
return new SimpleDraweeView(context);
}
@Override
public void displayImage(Context context, Object path, ImageView imageView) {
imageView.setImageURI(Uri.parse((String) path));
}
}
retrofit的工具類 RetrofitUtil
public class RetrofitUtil {
private final Retrofit retrofit;
private HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY);
private RetrofitUtil() {
retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(buildOkhttpClinet())
.build();
}
private OkHttpClient buildOkhttpClinet() {
return new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.addInterceptor(httpLoggingInterceptor)
.build();
}
//暴露外部的方法
public static RetrofitUtil getDefault() {
return SingleHolder._instant;
}
private static class SingleHolder {
private static final RetrofitUtil _instant = new RetrofitUtil();
}
//動態代理建立介面實現類
public <T> T create(Class<T> Clazz) {
return retrofit.create(Clazz);
}
}
mvp-model-IndexModel
public class IndexModel {
public Observable<Ad> getAd() {
return RetrofitUtil.getDefault().create(MyRetrofit.class).getAd();
}
public Observable<Catagory> getCatagory() {
return RetrofitUtil.getDefault().create(MyRetrofit.class).getCatagory();
}
public Observable<Detail> getDetail(String pid) {
return RetrofitUtil.getDefault().create(MyRetrofit.class).getDetail(pid);
}
public Observable<AddCart> getAddCart(String uid, String pid) {
return RetrofitUtil.getDefault().create(MyRetrofit.class).getAddCart(uid, pid);
}
}
mvp-presenter-IndexPresenter
public class IndexPresenter extends BasePresenter<IndexView> {
private IndexModel indexModel;
public IndexPresenter(IndexView view) {
super(view);
}
@Override
public void initModel() {
indexModel = new IndexModel();
}
public void getAd() {
indexModel.getAd()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Ad>() {
@Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
@Override
public void onNext(Ad ad) {
view.onSuccess(ad);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
public void getCatagory() {
indexModel.getCatagory()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Catagory>() {
@Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
@Override
public void onNext(Catagory catagory) {
view.onCatagorySuccess(catagory);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
mvp-view-IndexView
public interface IndexView extends IView{
void onSuccess(Ad ad);
void onCatagorySuccess(Catagory catagory);
}
推薦介面卡的佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.facebook.drawee.view.SimpleDraweeView
android:layout_gravity="center_horizontal"
android:id="@+id/tuijian_img"
android:layout_width="100dp"
android:layout_height="100dp"
app:placeholderImage="@drawable/ic_launcher_background" />
<TextView
android:maxLines="2"
android:id="@+id/tuijian_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_marginTop="5dp"
android:id="@+id/tuijian_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/red" />
</LinearLayout>
推薦的介面卡 TuijianAdapter
public class TuiJianAdapter extends RecyclerView.Adapter {
private List<Ad.TuijianBean.ListBean> list;
private Context context;
public TuiJianAdapter(List<Ad.TuijianBean.ListBean> list) {
this.list = list;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
context = parent.getContext();
View view = View.inflate(context, R.layout.tuijian_item, null);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
ViewHolder mHolder = (ViewHolder) holder;
final Ad.TuijianBean.ListBean bean = list.get(position);
//處理圖片url
String imgUrl = getImgUrl(bean.getImages());
mHolder.tuijianImg.setImageURI(Uri.parse(imgUrl));
mHolder.tuijianTitle.setText(bean.getTitle());
mHolder.tuijianPrice.setText("¥" + bean.getBargainPrice());
mHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra("pid",bean.getPid()+"");
context.startActivity(intent);
}
});
}
private String getImgUrl(String images) {
String[] split = images.split("\\|");
return split[0];
}
@Override
public int getItemCount() {
return list.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tuijian_img)
SimpleDraweeView tuijianImg;
@BindView(R.id.tuijian_title)
TextView tuijianTitle;
@BindView(R.id.tuijian_price)
TextView tuijianPrice;
ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
九宮格介面卡的佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
>
<com.facebook.drawee.view.SimpleDraweeView
android:id="@+id/jgg_img"
app:placeholderImage="@drawable/ic_launcher_background"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="@+id/jgg_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
九宮格的介面卡 Jggadapter
public class JggAdapter extends RecyclerView.Adapter {
private List<Catagory.DataBean> list;
public JggAdapter(List<Catagory.DataBean> list) {
this.list = list;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = View.inflate(parent.getContext(), R.layout.jgg_item, null);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
ViewHolder mHolder = (ViewHolder) holder;
final Catagory.DataBean bean = list.get(position);
mHolder.jggName.setText(bean.getName());
mHolder.jggImg.setImageURI(Uri.parse(bean.getIcon()));
}
@Override
public int getItemCount() {
return list.size();
}
static class ViewHolder extends RecyclerView.ViewHolder{
@BindView(R.id.jgg_img)
SimpleDraweeView jggImg;
@BindView(R.id.jgg_name)
TextView jggName;
ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
推薦跳轉的詳情頁面
detail的佈局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".mvp.view.activity.DetailActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="9">
<com.youth.banner.Banner
android:id="@+id/detail_banner"
android:layout_width="match_parent"
android:layout_height="350dp"></com.youth.banner.Banner>
<TextView
android:textStyle="bold"
android:id="@+id/detail_price"
android:textColor="@color/red"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:textColor="@color/black"
android:layout_marginTop="10dp"
android:id="@+id/detail_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="6"
android:orientation="horizontal">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/lianxi" />
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/dianpu" />
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/gouwuche" />
</LinearLayout>
<Button
android:id="@+id/detail_addcart"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="4"
android:background="@color/cheng"
android:gravity="center"
android:text="加入購物車"
android:textColor="@color/white" />
</LinearLayout>
</LinearLayout>
DetailActivity
public class DetailActivity extends BaseActivity<DetailPresenter> implements DetailView {
@BindView(R.id.detail_banner)
Banner detailBanner;
@BindView(R.id.detail_price)
TextView detailPrice;
@BindView(R.id.detail_title)
TextView detailTitle;
@BindView(R.id.detail_addcart)
Button detailAddcart;
private Detail.DataBean data;
private String pid;
private int uid;
@Override
public DetailPresenter providePresenter() {
return new DetailPresenter(this);
}
@Override
public int provideLayoutId() {
return R.layout.activity_detail;
}
@Override
public void initListener() {
}
@Override
public void initDate() {
pid = getIntent().getStringExtra("pid");
uid = getSharedPreferences("user", 0).getInt("uid", 0);
// Log.d("aaa", pid);
presenter.getDetai(pid);
}
private void initBanner() {
List<String> path = new ArrayList<>();
String images = data.getImages();
String[] split = images.split("\\|");
for (String s : split) {
path.add(s);
}
detailBanner.setImages(path)
.isAutoPlay(false)
.setImageLoader(new MyLoader())
.setBannerStyle(BannerConfig.NUM_INDICATOR)
.start();
}
@Override
public void onDetailSuccess(Detail detail) {
data = detail.getData();
//初始化banner
initBanner();
detailPrice.setText("¥" + data.getBargainPrice());
detailTitle.setText(data.getTitle());
}
@Override
public void onAddCartSuccess(AddCart addCart) {
Toast.makeText(DetailActivity.this,addCart.getMsg(),Toast.LENGTH_SHORT).show();
}
@OnClick(R.id.detail_addcart)
public void onViewClicked() {
//新增之前先判斷是否已登入
int i = getSharedPreferences("user", 0).getInt("islogin", 0);
if(i==1){
presenter.getAddCart(uid+"",pid);
}else {
Toast.makeText(DetailActivity.this,"登入後可以使用購物車",Toast.LENGTH_SHORT).show();
}
}
}
mvp-presenter-DetailPresenter
public class DetailPresenter extends BasePresenter<DetailView> {
private IndexModel indexModel;
public DetailPresenter(DetailView view) {
super(view);
}
@Override
public void initModel() {
indexModel = new IndexModel();
}
public void getDetai(String pid) {
indexModel.getDetail(pid)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Detail>() {
@Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
@Override
public void onNext(Detail detail) {
view.onDetailSuccess(detail);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
public void getAddCart(String uid,String pid) {
indexModel.getAddCart(uid,pid)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<AddCart>() {
@Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
@Override
public void onNext(AddCart addCart) {
view.onAddCartSuccess(addCart);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
mvp-view-DetailView
public interface DetailView extends IView {
void onDetailSuccess(Detail detail);
void onAddCartSuccess(AddCart addCart);
}