小追兵專欄
先聲明,下面效果完全可以用RecyclerView 簡單實現(xiàn)。不需要這么麻煩。
有時候我們需要如下圖效果:
我們只需要顯示6條數(shù)據(jù),在ListView下面顯示一個按鍵,用來清除ListView中的數(shù)據(jù)??墒俏覀儫o法實現(xiàn),我們的按鍵總是被擠壓到屏幕的最底部。我們?nèi)绾螌崿F(xiàn)呢?方法很簡單。
注意:這中方法,在數(shù)據(jù)超出一屏幕的時候,是能使用的,因為該listview不可以滑動。

QQ20160311-1@2x.png
網(wǎng)上找了也別的的方法,需要計算list中顯示條目的個數(shù),然后在在代碼中設置listview的高度。
這里看看我怎么實現(xiàn)的
我們的布局代碼:
<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翻墻賬號可以私聊。