Gallery左移

来源:互联网 发布:轩辕剑之骑兵进阶数据 编辑:程序博客网 时间:2024/04/30 06:45

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);}