Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

硅谷商城源码解析(四):分类页面的实现思路与核心技术

編輯:關於 Android 程式設計

一、前言

上一篇我们梳理了硅谷商城首页的关键技术点,这一篇把镜头转向分类页。分类页看起来朴素,其实集中了不少实战中高频出现的技巧:标签与分类栏的联动切换、屏幕自适应、左右联动的商品列表,以及横向滚动的热卖专区。

二、资源地址

受篇幅所限,完整的视频讲解与配套笔记可参考项目仓库:

https://github.com/atguigu01/Shopping

三、效果预览

四、技术详解

1. 用 FlycoTabLayout 实现标签与分类切换

顶部标签栏与左侧分类列表的联动,靠的是 FlycoTabLayout 这个开源控件。它自带指示器、下划线、缩放动画等样式,配合 ViewPager 或 Fragment 切换都能用,省去了自己写指示器动画的功夫。

项目地址:https://github.com/H07000223/FlycoTabLayout

2. 布局采用百分比适配

左侧分类固定占比、右侧商品区占剩余空间,用百分比布局比写死 dp 更稳妥,在不同分辨率设备上不容易跑版。

先引入依赖:

compile 'com.android.support:percent:23.3.0'

布局文件:

<android.support.percent.PercentRelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".type.fragment.ListFragment">

    <ListView
        android:id="@+id/lv_left"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:background="#11000000"
        android:scrollbars="none"
        app:layout_widthPercent="22%" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_right"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_toRightOf="@id/lv_left"
        app:layout_widthPercent="78%" />

</android.support.percent.PercentRelativeLayout>

这里有个容易踩的坑:使用 layout_widthPercent 时,layout_width 必须写成 0dp,否则百分比不生效。

3. 热卖类型横向滚动

热卖专区需要在有限高度里横向排布若干入口,最省事的做法就是 HorizontalScrollView 里塞一个横向的 LinearLayout,运行时再动态往容器里加子 View。

<HorizontalScrollView
    android:id="@+id/hsl_hot_right"
    android:scrollbars="none"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/ll_hot_right"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" />

</HorizontalScrollView>

4. 整体数据展示:仿京东分类页

最终结构是经典的左右联动:左侧用 ListView 展示一级分类,右侧用 RecyclerView 以分组形式展示该分类下的商品。左侧滚动时右侧跟着切换内容,右侧分组标题吸顶,交互逻辑与主流电商 App 保持一致。

这种写法的关键在于数据源的组织方式——把「一级分类 + 二级分组 + 商品列表」整理成一个可索引的数据结构,两个列表各自只关心自己那部分渲染,维护起来清爽很多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved