当前位置 : 主页 > 手机开发 > android >

Android购物分类效果实现

来源:互联网 收集:自由互联 发布时间:2021-05-17
本文实例为大家分享了Android购物分类效果展示的具体代码,供大家参考,具体内容如下 SecondActivity.java public class SecondActivity extends AppCompatActivity{ private ViewPager mPager; private RadioGroup mRad

本文实例为大家分享了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;
 }
}

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

网友评论