如何将第一个图库项目向左对齐



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

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

private void aligngallerytolleft(图库){

    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值传递给这个方法。

希望它对你有用。

提供的链接中的答案:https://stackoverflow.com/questions/4341158/android-align-first-item-in-gallery-to-the-left工作完全正常。问题是,我有包装画廊在framayout ,因此它不工作,当我把它改为RelativeLayout,它工作得很好。

最新更新