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

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

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

注意:这种方法,在数据超出一屏幕的时候,是能使用的,因为该listview不可以滑动。

这里写图片描述

网上找了也别的的方法,需要计算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效果。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值