一、上图
(图1)
(图2)
二、场景描述
当点击下拉箭头,弹出PopupWindow弹窗,当点击弹窗中的某一item后(如图1),水平滑动列表(图2)向左或向右滑动到对应的项。
三、使用的控件
水平滑动列表(图2顶部)使用的控件是HorizontalScrollView嵌套GridView的方式书写的逻辑,xml文件如下:
<!-- 水平滑动控件 -->
<HorizontalScrollView
android:id="@+id/hsv_category"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<GridView
android:id="@+id/gv_category"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="@dimen/dp10"
android:background="@android:color/transparent"
android:listSelector="@android:color/transparent"
android:numColumns="auto_fit"
android:scrollbars="none"
android:stretchMode="spacingWidthUniform" />
</LinearLayout>
</HorizontalScrollView>
四、需要处理的问题
当popupWindow弹窗在消失时,需要解决HorizontalScrollView向左滑或者向右滑的问题。
五、解决思路
HorizontalScrollView中GridView的item宽度是可以计算或者通过指定固定宽度取得。因为弹窗中也使用的是GridView,填充的适配器数据与水平滑动控件的数据是一样的,那么适配器中当前项curentPosition也是一样的,当弹窗消失的时候,可以通过获取PopupWindow中的curentPosition,然后设置水平滑动控件中GridView的curentPosition,即设置当前选中项.
如何判断是需要向左滑动还是需要向右滑动呢?
因为水平滑动控件默认展示4项内容(position从0开始),那么curentPosition如果>3的时候,则表示当前需要向右滑动,如果curentPosition<3,则表示需要向左滑动。以下是处理左滑与右滑的逻辑代码:
// 如果未显示弹窗前的索引与弹窗消失后的索引没有变化,则视为不需要请求接口数据的情况
if (selectPosition != shopCategoryPopupWindow.getSelectPosition()) {
// 设置类目选中项
selectPosition = shopCategoryPopupWindow.getSelectPosition();
// 如果当前项 > 3则表示需要向右滑动,如果当前位置<3则表示需要向左滑动
if (selectPosition > 3) {
moveToRight();
} else if (selectPosition < 3) {
moveToLeft();
}
shopCategoryAdapter.setCurentSelectPosition(selectPosition);
shopCategoryAdapter.notifyDataSetChanged();
// 请求店铺列表数据
clearShopListData();
requestShopList(selectPosition);
} else {
shopCategoryAdapter.setCurentSelectPosition(selectPosition);
shopCategoryAdapter.notifyDataSetChanged();
}
/**
* 向左滑动
*/
protected void moveToLeft() {
itemWidth = (int) ModelUtil.calcDensityUnit(ShopListActivity.this, 80);
final int scrollX = -Math.abs((selectPosition - 3) * itemWidth);
hsvCategory.smoothScrollBy(scrollX, 0);
}
/**
* 向右滑动
*/
protected void moveToRight() {
itemWidth = (int) ModelUtil.calcDensityUnit(ShopListActivity.this, 80);
final int scrollX = Math.abs((selectPosition - 3 + 4) * itemWidth);
hsvCategory.smoothScrollBy(scrollX, 0);
}