【问题标题】:add space to top and bottom of ListView so top and bottom item can be centered在 ListView 的顶部和底部添加空间,以便顶部和底部项目可以居中
【发布时间】:2012-12-11 02:29:11
【问题描述】:

我的 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>

【问题讨论】:

    标签: android listview


    【解决方案1】:

    我找不到剪辑问题的解决方案,因此我向 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 并使用更大的页眉和页脚重新创建它。

    我希望这可以帮助某人摆脱数小时的沮丧:)

    【讨论】:

      猜你喜欢
      • 2020-10-14
      • 2014-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-01
      • 1970-01-01
      • 2012-07-15
      相关资源
      最近更新 更多