ListView 下拉刷新

本文介绍ListView下拉刷新的实现原理,通过动态调整ListView第一项的paddingTop值来完成。文中详细解释了ListView的相关方法,如getFirstVisiblePosition()、getLastVisiblePosition()等,并提供了测量视图高度和计算移动位置的具体代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看了ListView的下拉刷新,原理是动态调整 Listview的第一行的paddingTop值,然后就能实现ListView的下拉刷新。

 

有下面几个ListView常用的方法


getFirstVisiblePosition() 取得界面上第一个显示的位置
getLastVisiblePosition() 取得界面上最后一个显示的位置
setSelection(int position)  设置当前选中的位置,List会自动调至该位置

sdetVerticalScrollBarEnable(true)   设置scrollbar不能往下拉

getMeasuredHeight()    达到测量的长度,要在下面的measureView调用之后再调用,不然得到的是0
getBottom()   得得到view的最下面在屏幕中的位置
getPaddingTop()

 

还有两个方法也不错,测量view的高度

private void measureView(View child) {
		ViewGroup.LayoutParams p = child.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
		}

		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
					MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0,
					MeasureSpec.UNSPECIFIED);
		}
		
		Log.d(TAG, "childWidthSpec:" + childWidthSpec + " childHeightSpec:" + childHeightSpec);
		child.measure(childWidthSpec, childHeightSpec);
	}
 

在OnTouchEvent 的Move事件中计算出当下移动的位置

 

private void refreshHead(MotionEvent e){
		int point = e.getHistorySize();
		for(int i = 0; i < point; i ++){
			int historicalY = (int) e.getHistoricalY(i);
			int topPadding = (int)((historicalY - mLastPositionY - mRefreshViewHeight) / 1.7);
			mRefreshView.setPadding(mRefreshView.getPaddingLeft(), topPadding, 
					mRefreshView.getPaddingRight(), mRefreshView.getPaddingBottom());
			
			if(getFirstVisiblePosition() == 0){
				if(mRefreshView.getBottom() > 50){
					mListState = PULL_READ_REFRESH;
					displayRefreshView();
				} else {
					mListState = PULL_REFRESH;
				}
			}
			
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值