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效果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章