Android购物分类效果实现

本文实例为大家分享了Android购物分类效果展示的具体代码,供大家参考,具体内容如下

SecondActivity.java

public class SecondActivity extends AppCompatActivity{
  private ViewPager mPager;
  private RadioGroup mRadioGroup;

  @Override
  protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);

     mPager = findViewById(R.id.pager);
     mRadioGroup = findViewById(R.id.group);

     mPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
       @Override
       public Fragment getItem(int position) {
         Fragment fragment=null;

         switch (position){
           case 0:
             fragment = new Afrag();
             break;
           case 1:
             fragment = new Bfrag();
             break;
           case 2:
             fragment = new Cfrag();
             break;
         }
         return fragment;
       }

       @Override
       public int getCount() {
         return 3;
       }
     });

     mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
       @Override
       public void onCheckedChanged(RadioGroup radioGroup, int i) {
         switch (i){
           case R.id.r1:
             mPager.setCurrentItem(0);
             break;
           case R.id.r2:
             mPager.setCurrentItem(1);
             break;
           case R.id.r3:
             mPager.setCurrentItem(2);
             break;
         }
       }
     });
  }
}

secondActivity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

  <android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="13"/>

  <RadioGroup
    android:id="@+id/group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="horizontal">

    <RadioButton
      android:id="@+id/r1"
      android:layout_width="wrap_content"
      android:layout_weight="1"
      android:layout_height="match_parent"
      android:button="@null"
      android:gravity="center"
      android:text="首页"/>

    <RadioButton
      android:id="@+id/r2"
      android:layout_width="wrap_content"
      android:layout_weight="1"
      android:layout_height="match_parent"
      android:button="@null"
      android:gravity="center"
      android:text="分类"/>

    <RadioButton
      android:id="@+id/r3"
      android:layout_width="wrap_content"
      android:layout_weight="1"
      android:layout_height="match_parent"
      android:button="@null"
      android:gravity="center"
      android:text="购物车"/>
  </RadioGroup>
</LinearLayout>

Afrag.java

public class Afrag extends Fragment{
  private RecyclerView mRecyclerView;
  public String urlString="http://www.wanandroid.com/tools/mockapi/6523/restaurants_offset_0_limit_4 ";

  @Nullable
  @Override
  public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = View.inflate(getActivity(), R.layout.afrag, null);
    mRecyclerView = view.findViewById(R.id.rv);
    initData();

    return view;
  }

  private void initData() {
    OkHttps okHttps = OkHttps.getInstance();

    okHttps.doGet(urlString, new OkHttps.OkCallback() {
      @Override
      public void onResponse(String json) { //瀑布流

        PubuBean pubuBean = new Gson().fromJson(json,PubuBean.class);
        List<PubuBean.DataBean> results = pubuBean.getData();

        PubuAdapter pubuAdapter = new PubuAdapter(getActivity());
        pubuAdapter.setDatas(results);
        mRecyclerView.setAdapter(pubuAdapter);

        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(manager);
      }

      @Override
      public void onFailure(Exception e) {

      }
    });

  }
}

afrag.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <android.support.v7.widget.RecyclerView
    android:id="@+id/rv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

</LinearLayout>

PubuAdapter.java

public class PubuAdapter extends RecyclerView.Adapter<PubuAdapter.ViewHolder>{
  private Context mContext;
  ArrayList<PubuBean.DataBean> list;

  public PubuAdapter(Context context) {
    mContext = context;
    list = new ArrayList<>();
  }

  public void setDatas(List<PubuBean.DataBean> datas) {
    list.addAll(datas);

  }
  @NonNull
  @Override
  public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = View.inflate(mContext, R.layout.pbitem, null);
    ViewHolder holder = new ViewHolder(view);
    return holder;
  }

  @Override
  public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

    holder.mTextView.setText(list.get(position).getName());
    Glide.with(mContext).load(list.get(position).getPic_url()).into(holder.mImageView);

  }

  @Override
  public int getItemCount() {
    return list.size();
  }

  public class ViewHolder extends RecyclerView.ViewHolder {
    ImageView mImageView;
    TextView mTextView;
    public ViewHolder(View itemView) {
      super(itemView);
      mImageView = itemView.findViewById(R.id.image);
      mTextView = itemView.findViewById(R.id.t1);

    }
  }
}

Bfrag.java

public class Bfrag extends Fragment{
  private RecyclerView mRecyclerView;
  LeftAdapter adapter;
  String urlString="http://www.zhaoapi.cn/product/getCatagory";
  String urlString2="http://www.zhaoapi.cn/product/getProductCatagory";
  private RecyclerView mRecyclerView2;

  @Nullable
  @Override
  public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = View.inflate(getActivity(), R.layout.bfrag, null);//分类页面

    mRecyclerView = view.findViewById(R.id.rv1); //左侧列表

    mRecyclerView2 = view.findViewById(R.id.rv2); //右
    initData();

    return view;
  }

  private void initData() {
    OkHttps okHttps = OkHttps.getInstance();

    okHttps.doGet(urlString, new OkHttps.OkCallback() {
      @Override
      public void onResponse(String json) { //瀑布流

        LeftBean leftBean = new Gson().fromJson(json,LeftBean.class);
        List<LeftBean.DataBean> results = leftBean.getData();

        adapter = new LeftAdapter(getActivity());
        adapter.setDatas(results);

        mRecyclerView.setAdapter(adapter);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));

        adapter.setOnItemClickListener(new LeftAdapter.OnItemClickListener() {
          @Override
          public void onItemClick(int position) {

            //Toast.makeText(getActivity(),position+"",Toast.LENGTH_SHORT).show();
            rigth(position);
          }
        });
      }

      @Override
      public void onFailure(Exception e) {

      }
    });
  }

  public void rigth(int position){
    HashMap<String, String> map = new HashMap<>();
    map.put("cid",position+1+"");

    OkHttps.getInstance().doPost(urlString2,map,new OkHttps.OkCallback() {
      @Override
      public void onResponse(String json) {

        RightBean rightBean = new Gson().fromJson(json,RightBean.class);
        List<RightBean.DataBean> results = rightBean.getData();

        RightAdapter rightAdapter = new RightAdapter(getActivity());
        rightAdapter.setDatas(results);

        mRecyclerView2.setAdapter(rightAdapter);

        mRecyclerView2.setLayoutManager(new GridLayoutManager(getActivity(),3));
      }

      @Override
      public void onFailure(Exception e) {

      }
    });
  }
}

bfrag.xml

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv1"
    android:layout_width="0dp"
    android:layout_weight="2"
    android:layout_height="match_parent"/>

  <android.support.v7.widget.RecyclerView
    android:id="@+id/rv2"
    android:layout_width="0dp"
    android:layout_weight="10"
    android:layout_height="match_parent"/>

</LinearLayout>

LeftAdapter.java

public class LeftAdapter extends RecyclerView.Adapter<LeftAdapter.ViewHolder>{
  private Context mContext;
  ArrayList<LeftBean.DataBean> list;

  public LeftAdapter(Context context) {
    mContext = context;
    list = new ArrayList<>();
  }

  public void setDatas(List<LeftBean.DataBean> datas) {
    list.addAll(datas);

  }

  public interface OnItemClickListener{  //自定义接口回调设置点击事件
    void onItemClick(int position);
  }

  private OnItemClickListener mOnItemClickListener;

  public void setOnItemClickListener(OnItemClickListener onItemClickListener){
    mOnItemClickListener=onItemClickListener;
  }

  @NonNull
  @Override
  public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = View.inflate(mContext, R.layout.leftitem, null);
    ViewHolder holder = new ViewHolder(view);
    return holder;
  }

  @Override
  public void onBindViewHolder(@NonNull final ViewHolder holder, int position) {

    holder.mTextView.setText(list.get(position).getName());

    holder.itemView.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View view) {
        int position1 = holder.getLayoutPosition();
        mOnItemClickListener.onItemClick(position1);
      }
    });
  }

  @Override
  public int getItemCount() {
    return list.size();
  }

  public class ViewHolder extends RecyclerView.ViewHolder {
    TextView mTextView;
    public ViewHolder(View itemView) {
      super(itemView);
      mTextView = itemView.findViewById(R.id.text1);

    }
  }
}

RightAdapter.java

public class RightAdapter extends RecyclerView.Adapter<RightAdapter.ViewHolder>{
  private Context mContext;
  ArrayList<RightBean.DataBean> list;

  public RightAdapter(Context context) {
    mContext = context;
    list = new ArrayList<>();
  }

  public void setDatas(List<RightBean.DataBean> datas) {
    list.addAll(datas);

  }
  @NonNull
  @Override
  public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = View.inflate(mContext, R.layout.rightitem, null);
    ViewHolder holder = new ViewHolder(view);
    return holder;
  }

  @Override
  public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    holder.mTextView.setText(list.get(position).getName());
    Glide.with(mContext).load(list.get(position).getList().get(position).getIcon()).into(holder.mImageView);
  }

  @Override
  public int getItemCount() {
    return list.size();
  }

  public class ViewHolder extends RecyclerView.ViewHolder {
    ImageView mImageView;
    TextView mTextView;

    public ViewHolder(View itemView) {
      super(itemView);
      mImageView = itemView.findViewById(R.id.image1);
      mTextView = itemView.findViewById(R.id.text2);

    }
  }
}

OkHttps.java

public class OkHttps {
  Handler handler;
  private final OkHttpClient mOkHttpClient;
  private static OkHttps mOkHttps;

  private OkHttps() {
    handler = new Handler(Looper.getMainLooper());

    LoggingInterceptor loggingInterceptor = new LoggingInterceptor(); //日志拦截器
    mOkHttpClient = new OkHttpClient.Builder()
        .addInterceptor(loggingInterceptor)  //设置日志拦截器
        .connectTimeout(5000, TimeUnit.MILLISECONDS)
        .readTimeout(5000,TimeUnit.MILLISECONDS)
        .writeTimeout(5000,TimeUnit.MILLISECONDS)
        .build();

  }

  public static OkHttps getInstance(){
    if (mOkHttps==null){
      synchronized (OkHttps.class){
        if (mOkHttps==null){
          return mOkHttps=new OkHttps();
        }
      }
    }
    return mOkHttps;
  }

  public interface OkCallback{
    void onResponse(String json);

    void onFailure(Exception e);

  }

  public void doPost(String url, Map<String,String> map, final OkCallback okCallback){
    FormBody.Builder builder = new FormBody.Builder();
    if (map!=null){
      for (String key:map.keySet()){
        builder.add(key,map.get(key));
      }
    }

    FormBody formBody = builder.build();

    final Request request = new Request.Builder()
        .post(formBody)
        .url(url)
        .build();

    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {
      @Override
      public void onFailure(Call call, final IOException e) {
        if (okCallback!=null){
          handler.post(new Runnable() {
            @Override
            public void run() {

              okCallback.onFailure(e);
            }
          });
        }
      }

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

        try {
          if (response!=null && response.isSuccessful()){
            final String json = response.body().string();
            handler.post(new Runnable() {
              @Override
              public void run() {
                if (okCallback!=null){

                  okCallback.onResponse(json);
                  return;
                }
              }
            });
          }
        }catch (IOException e){
          e.printStackTrace();
        }
        if (okCallback!=null){
          okCallback.onFailure(new Exception("网络异常"));
        }
      }
    });

  }
  public void doGet(String url, final OkCallback okCallback){
    Request request = new Request.Builder()
        .url(url)
        .build();

    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {
      @Override
      public void onFailure(Call call, final IOException e) {
        if (okCallback != null) {
          //切换到主线程
          handler.post(new Runnable() {
            @Override
            public void run() {
              okCallback.onFailure(e);
            }
          });
        }
      }

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

        try {
          if (response != null && response.isSuccessful()) {
            final String json = response.body().string();
            handler.post(new Runnable() {
              @Override
              public void run() {
                if (okCallback != null) {
                  okCallback.onResponse(json);
                }

              }
            });
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    });
  }
}

依赖

implementation 'com.google.code.gson:gson:2.8.5'
  implementation 'com.squareup.okhttp3:okhttp:3.12.0'
  implementation 'com.android.support:recyclerview-v7:27.1.1'
  implementation 'com.github.bumptech.glide:glide:3.7.0'

LoggingInterceptor.java //拦截器

class LoggingInterceptor implements Interceptor {
 @Override
 public Response intercept(Chain chain) throws IOException {
  //拿到Request对象
  Request request = chain.request();

  long t1 = System.nanoTime();
  System.out.println(" request = " + String.format("Sending request %s on %s%n%s",
      request.url(), chain.connection(), request.headers()));

  //拿到Response对象
  Response response = chain.proceed(request);

  long t2 = System.nanoTime();
  //得出请求网络,到得到结果,中间消耗了多长时间
  System.out.println("response " + String.format("Received response for %s in %.1fms%n%s",
      response.request().url(), (t2 - t1) / 1e6d, response.headers()));
  return response;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Android实现仿淘宝购物车增加和减少商品数量功能demo示例

    本文实例讲述了Android实现仿淘宝购物车增加和减少商品数量功能.分享给大家供大家参考,具体如下: 在前面一篇<Android实现的仿淘宝购物车demo示例>中,小编简单的介绍了如何使用listview来实现购物车,但是仅仅是简单的实现了列表的功能,随之而来一个新的问题,买商品的时候,我们可能不止想买一件商品,想买多个,或许有因为某种原因点错了,本来想买一件来着,小手不小心抖了一下,把数量错点成了三个,这个时候就涉及到一个新的功能,那就是增加和减少商品的数量,今天这篇博文,小编就来和小伙伴们

  • Android组合式自定义控件实现购物车加减商品操作

    本文实例为大家分享了Android实现购物车加减商品操作的具体代码,供大家参考,具体内容如下 MainActivity.java public class MainActivity extends AppCompatActivity { private Addand mAddand; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setConte

  • Android中实现淘宝购物车RecyclerView或LIstView的嵌套选择的逻辑

    使用了RecyclerView嵌套RecyclerView的方案. 购物车的第一个界面为RecyclerView,每个Item里面包含一个店铺.在Item中使用RecyclerView包含店铺和店铺的多个商品. 实现思路: 使用接口回调将第二个adapter的商品选择的监听事件回调给第一个adapter后再在第一个adapter中回调给MainActivity. 使用接口回调将第一个adapter的商品选择的监听事件回调给MainActivity. 在MainActivity中处理第一个adap

  • Android实现简单购物车功能

    本文实例为大家分享了Android实现购物车功能的具体代码,供大家参考,具体内容如下 MainActivity布局: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"

  • Android把商品添加到购物车的动画效果(贝塞尔曲线)

    当我们写商城类的项目的时候,一般都会有加入购物车的功能,加入购物车的时候会有一些抛物线动画,具体代码如下: 实现效果如图: 思路: 确定动画的起终点 在起终点之间使用二次贝塞尔曲线填充起终点之间的点的轨迹 设置属性动画,ValueAnimator插值器,获取中间点的坐标 将执行动画的控件的x.y坐标设为上面得到的中间点坐标 开启属性动画 当动画结束时的操作 难点: PathMeasure的使用 - getLength() - boolean getPosTan(float distance, f

  • Android仿外卖购物车功能

    先看看效果图: 知识点分析 效果图来看不复杂内容并没多少,值得介绍一下的知识点也就下面几个吧 - 列表标题悬停 - 左右列表滑动时联动 - 添加商品时的抛物线动画 - 底部弹出购物车清单 - 数据的同步 另外就是实现效果的时候可能会遇到的几个坑... 布局很简单直接进入代码 1:列表标题悬停 现在做项目列表什么的基本抛弃了ListView改用RecyclerView,上篇博客中的标题悬停也是使用了一个RecyclerView的开源项目sticky-headers-recyclerview,不过写

  • Android实现的仿淘宝购物车demo示例

    本文实例讲述了Android实现的仿淘宝购物车.分享给大家供大家参考,具体如下: 夏的热情渐渐退去,秋如期而至,丰收的季节,小编继续着实习之路,走着走着,就走到了购物车,逛过淘宝或者是京东的小伙伴都知道购物车里面的宝贝可不止一件,对于爱购物的姑娘来说,购物车里面的商品恐怕是爆满,添加不进去了,以前逛淘宝的时候,小编没有想过要怎么样实现购物车,就知道在哪儿一个劲儿的逛,但是现在不一样了,小编做为一个开发者,想的就是该如何实现,捣鼓了两天的时间,用listview来实现,已经有模有样了,现在小编就来

  • Android仿饿了么加入购物车旋转控件自带闪转腾挪动画的按钮效果(实例详解)

    概述 在上文,酷炫Path动画已经预告了,今天给大家带来的是利用 纯自定义View,实现的仿饿了么加入购物车控件,自带闪转腾挪动画的按钮. 效果图如下: 图1 项目中使用的效果,考虑到了View的回收复用, 并且可以看到在RecyclerView中使用,切换LayoutManager也是没有问题的, 图2 Demo效果,测试各种属性值 注意,本控件非继承自ViewGroup,而是纯自定义View实现.理由如下: 1 减少布局层级,从而提高性能 2 文字和图形纯draw,用到什么draw什么,没有

  • Android实现购物车功能

    最近看了一些淘宝购物车的demo,于是也写了一个. 效果图如下: 主要代码如下: actvity中的代码: public class ShoppingCartActivity extends BaseActivity { private List<Test> data; private ListView mListView; private ShoppingCartAdapter adapter; private RelativeLayout rlRefresh; private TextVi

  • Android实现购物车整体页面逻辑详解

    本文为大家讲解了Android实现购物车的整体页面逻辑,供大家参考,具体内容如下 MainActivity.java public class MainActivity extends AppCompatActivity implements View.OnClickListener{ String url = "http://www.zhaoapi.cn/product/getCarts"; private ExpandableListView el_cart; private Ch

随机推荐