【Android】修改Gallery中图片的显示顺序

在Gallery的开发中,可能会遇到图片相互重叠的需求,即:一张图片压在另一张图片的上面
由于在Gallery的默认实现中,图片的重叠顺序是这样的:
左边图片压在右边图片的上面,中间被选中的图片压在所有图片的最上面
因此,如果在这种情况下想要修改Gallery中图片的显示顺序,就需要重新定义Gallery中图片的显示顺序规则

在Gallery中,图片的显示顺序规则是一个名为getChildDrawingOrder方法来实现的
该方法需要接收2个参数,分别为childCount与order,此方法的返回值为childIndex
其中各参数的含义为:
childCount表示可视图片的数量
childIndex表示图片在可视图片中的下标
order表示图片被显示出来的顺序,此数值越大,说明图片被显示出来的越晚,显示位置也就越靠前

假设当前屏幕上只能显示出来5张图片,那么按照Gallery的默认设置,上面三个参数的对应关系如下:

childCount=5:     
childIndex0 1 2 3 4
order01423

在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;
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值