2013-02-26 63 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你的價值此方法。

希望,它會爲你工作。

相關問題