在Gallery的开发中,可能会遇到图片相互重叠的需求,即:一张图片压在另一张图片的上面
由于在Gallery的默认实现中,图片的重叠顺序是这样的:
左边图片压在右边图片的上面,中间被选中的图片压在所有图片的最上面
因此,如果在这种情况下想要修改Gallery中图片的显示顺序,就需要重新定义Gallery中图片的显示顺序规则
在Gallery中,图片的显示顺序规则是一个名为getChildDrawingOrder方法来实现的
该方法需要接收2个参数,分别为childCount与order,此方法的返回值为childIndex
其中各参数的含义为:
childCount表示可视图片的数量
childIndex表示图片在可视图片中的下标
order表示图片被显示出来的顺序,此数值越大,说明图片被显示出来的越晚,显示位置也就越靠前
假设当前屏幕上只能显示出来5张图片,那么按照Gallery的默认设置,上面三个参数的对应关系如下:
childCount=5: | |||||
childIndex | 0 | 1 | 2 | 3 | 4 |
order | 0 | 1 | 4 | 2 | 3 |
在Gallery中,默认的图片显示顺序的实现代码如下,如需修改图片的显示顺序,则重写此方法即可
@Override
protected int getChildDrawingOrder(int childCount, int order) {
setChildrenDrawingCacheEnabled(true);
int mFirstPosition = getFirstVisiblePosition();
int mSelectedPosition = computeHorizontalScrollOffset();
int selectedIndex = mSelectedPosition - mFirstPosition;
// Just to be safe
if (selectedIndex < 0) return order;
if (order== childCount - 1) {
// Draw the selected child last
return selectedIndex;
} else if (order >= selectedIndex) {
// Move the children after the selected child earlier one
return order + 1;
} else {
// Keep the children before the selected child the same
return order;
}
}
为了更易于进行理解,下面给出重写后的一个方法,此方法定义的图片显示顺序为:
中间的图片显示在最前端,靠近两边的图片显示在靠近中间的图片的前端
@Override
protected int getChildDrawingOrder(int childCount, int order) {
setChildrenDrawingCacheEnabled(true);
int mFirstPosition = getFirstVisiblePosition();
int mSelectedPosition = computeHorizontalScrollOffset();
int selectedIndex = mSelectedPosition - mFirstPosition;
// Just to be safe
if (selectedIndex < 0) return i;
if (order == childCount - 1) {
// Draw the selected child last
return selectedIndex;
} else if (order >= selectedIndex) {
// Move the children after the selected child from last to the selected
return (childCount - 1) - (order - selectedIndex);
} else {
// Keep the children before the selected child the same
return order;
}
}
}