如何将第一个画廊项目对齐到左侧?

时间:2013-02-26 08:49:19

标签: android android-gallery

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

但这对2.3.x设备不起作用。 我怎样才能实现它?

2 个答案:

答案 0 :(得分:2)

private void 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中的值传递给此方法。

希望,它会对你有用。

答案 1 :(得分:0)

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