如何将第一个图库项目对齐到左侧?
问题描述:
默认情况下,图库居中对齐。我想要的行为是左对齐父布局中的第一个项目而不是居中。如何做到这一点? 我也通过链接:https://*.com/questions/4341158/android-align-first-item-in-gallery-to-the-left如何将第一个图库项目对齐到左侧?
但是,这不适用于2.3.x设备。 我该如何实现它?
答
该链接提供的答案:https://*.com/questions/4341158/android-align-first-item-in-gallery-to-the-left工作得很好。问题是我有包装在FrameLayout中的画廊,因此它不工作时,我改变它为RelativeLayout,它工作正常。
+0
死链接404错误 – 2017-09-12 17:37:50
答
私人无效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你的价值此方法。
希望,它会为你工作。
答案建议在添加的链接不适用于HTC 2.3.3设备以及Kindle Fire。 – Nitin4Android 2013-02-26 09:01:52