2

默认情况下,图库是居中对齐的。我想要的行为是左对齐父布局中的第一项而不是居中。怎么做?我也浏览了链接:https ://stackoverflow.com/questions/4341158/android-align-first-item-in-gallery-to-the-left

但这不适用于 2.3.x 设备。我怎样才能实现它?

4

2 回答 2

2

私人无效alignGalleryToLeft(画廊画廊){

    WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

    int galleryWidth = manager.getDefaultDisplay().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 = getsize(105);
    int spacing = getsize(10);

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

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

getsize() 是一个方法:

public int getsize(int sizeInDip) {
    DisplayMetrics metrics = new DisplayMetrics();
    metrics = getResources().getDisplayMetrics();
    return (int) ((sizeInDip * metrics.density) + 0.5);
}

将您在 DPI 中的值传递给此方法。

希望,它会为你工作。

于 2013-07-20T08:26:41.283 回答
0

提供的链接中的答案:https ://stackoverflow.com/questions/4341158/android-align-first-item-in-gallery-to-the-left工作得很好。问题是我将 Gallery 包装在 FrameLayout 中,因此当我将其更改为 RelativeLayout 时它无法正常工作,它工作正常。

于 2013-02-26T09:50:20.247 回答