2013-02-26 78 views
2

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

但是,这不适用于2.3.x设备。 我该如何实现它?

+0

答案建议在添加的链接不适用于HTC 2.3.3设备以及Kindle Fire。 – Nitin4Android 2013-02-26 09:01:52

回答

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你的价值此方法。

希望,它会为你工作。