在ListView的顶部和底部添加空格,以便顶部和底部项目可以居中

时间:2012-12-11 02:29:11

标签: android 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>

1 个答案:

答案 0 :(得分: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并使用更大的页眉和页脚重新创建它。

我希望这可以帮助某些人免受数小时的挫折:)