ListView在显示较少数据是,高度由item的个数决定,wrap_content有效

小追兵专栏

先声明,下面效果完全可以用RecyclerView 简单实现。不需要这么麻烦。

有时候我们需要如下图效果:

我们只需要显示6条数据,在ListView下面显示一个按键,用来清除ListView中的数据。可是我们无法实现,我们的按键总是被挤压到屏幕的最底部。我们如何实现呢?方法很简单。

注意:这中方法,在数据超出一屏幕的时候,是能使用的,因为该listview不可以滑动。
QQ20160311-1@2x.png

网上找了也别的的方法,需要计算list中显示条目的个数,然后在在代码中设置listview的高度。

这里看看我怎么实现的
我们的布局代码:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/search_title_layout"
        android:orientation="vertical">

        <com.xis.read.view.ListViewForScrollView
            android:id="@+id/lv_history"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/tv_clear_history"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/selector_common_gray_background"
            android:gravity="center"
            android:padding="10dp"
            android:text="@string/claer_history"
            android:textColor="@color/readpage_rose" />
    </LinearLayout>

上面的重要的只有一条ListView的高度用wrap_content

接下来我们只要自定义ListView就好了。这个自定义ListView也可以用于ScrollView中嵌套使用

package cn.xs.reader.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

/**
 * Created by Saud on 16/2/15.
 */
public class ListViewForScrollView extends ListView {
    public ListViewForScrollView(Context context) {
        super(context);
    }

    public ListViewForScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ListViewForScrollView(Context context, AttributeSet attrs,
                                 int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    /**
     * 重写该方法,达到使ListView适应ScrollView的效果
     */
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }


}

这就解决了我们想要的Listview 的 wrap_content效果。

最后:有需要Shadowsock翻墙账号可以私聊。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容