2012-12-11 234 views
0

當我們的ListView項目被選中時需要居中,但頂部和底部項目停止在列表的頂部或底部。我如何將頂部和底部物品置於中心位置?在ListView的頂部和底部添加空間,以便頂部和底部項目可以居中

這裏是我的測試佈局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/parent" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:clipChildren="false" 
     android:clipToPadding="false" 
     android:gravity="top" > 

     <ListView 
      android:id="@+id/listview" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_centerVertical="true" 
      android:clipChildren="false" 
      android:clipToPadding="false" > 
     </ListView> 

    </RelativeLayout> 

回答

3

我無法找到一個解決剪裁問題,所以我與添加頁眉和頁腳到ListView去了。我改變了我的ListView的高度回match_parent,然後使用我的ListView的父視圖POST方法,我能計算我的頁眉和頁腳的高度,像這樣:

// this call should be included in the onCreate method 
// the post method is called after parentView is ready to be added 
// so the parentView's height and width can be used 
parentView.post(addSpace(parentView, myListView)); 

private Runnable addSpace(final RelativeLayout parent, final ListView list) { 
    return new Runnable(){ 
     public void run() { 
      // create list adapter here or in the onCreate method 
      // R.layout.list_item refers to my custom xml layout file 
      adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.list_item, values); 
      // calculate size and add header and footer BEFORE applying adapter 
      // listItemHeight was calculated previously 
      spacerSize = (parent.getHeight()/2) - (listItemHeight/2); 
      list.addHeaderView(getSpacer(), null, false); 
      list.addFooterView(getSpacer(), null, false); 
      list.setAdapter(adapter); 
     } 
    } 
} 

// I used a function to create my spacers 
private LinearLayout getSpacer(){ 
    // I used padding instead of LayoutParams thinking it would be easier to 
    // change in the future. It wasn't, but still made resizing my spacer easy 
    LinearLayout spacer = new LinearLayout(MainActivity.this); 
        spacer.setOrientation(LinearLayout.HORIZONTAL); 
        spacer.setPadding(parentView.getWidth(), spacerSize, 0, 0); 
    return spacer; 
} 

使用這種方法我能在我的ListView的頂部和底部添加適當的間距,所以當我一直滾動到頂部時,頂部項目出現在我的視圖中心。

問題:我的應用程序允許用戶隱藏底部界面元素,這應該讓我的父母更高。我正在制定一種方法來使頁眉和頁腳動態變高,但我可能需要簡單地刪除ListView並用較大的頁眉和頁腳重新創建它。

我希望這可以幫助一個人從幾小時的挫折:)