Gallery左移

http://www.marvinlabs.com/2011/06/proper-layout-gravity-gallery-widget/

Proper layout gravity for the Gallery widget

The gallery widget in Android is the closest match you can find for an horizontal ListView. However, this widget does not support properly the gravity attribute to specify whether we would like the first selected item to be centered (as in the default behaviour) or aligned to the left (currently not possible). The short code snippet below allows just to do that.

The first gallery item is aligned to the center of the Gallery widget (default behaviour)

The first gallery item is aligned to the left of the Gallery widget

The work-around consists in changing the gallery left margin at run time in order to make it believe it is wider than it thinks. Here is how to do it:

/**
 * Align the first gallery item to the left.
 *
 * @param parentView The view containing the gallery widget (we assume the gallery width
 *                   is set to match_parent)
 * @param gallery The gallery we have to change
 */
private void alignGalleryToLeft(View parentView, Gallery gallery) {
    int galleryWidth = parentView.getWidth();

    // We are taking the item widths and spacing from a dimension resource because:
    // 1. No way to get spacing at runtime (no accessor in the Gallery class)
    // 2. There might not yet be any item view created when we are calling this
    // function
    int itemWidth = context.getResources()
            .getDimensionPixelSize(R.dimen.gallery_item_width);
    int spacing = context.getResources()
            .getDimensionPixelSize(R.dimen.gallery_spacing);

    // The offset is how much we will pull the gallery to the left in order to simulate
    // left alignment of the first item
    int offset;
    if (galleryWidth <= itemWidth) {
        offset = galleryWidth / 2 - itemWidth / 2 - spacing;
    } else {
        offset = galleryWidth - itemWidth - 2 * spacing;
    }
    offset = 0;

    // Now update the layout parameters of the gallery in order to set the left margin
    MarginLayoutParams mlp = (MarginLayoutParams) gallery.getLayoutParams();
    mlp.setMargins(-offset, mlp.topMargin, mlp.rightMargin, mlp.bottomMargin);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值