居中滚动的Recyclerview

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012591964/article/details/51384721

RecyclerView出现已经有一段时间了,相信大家肯定不陌生了,大家可以通过导入support-v7对其进行使用。

      一定程度上取代了listview,gridview的使用。

      下面介绍一下RecyclerView的居中滚动,只需要继承RecyclerView。

      然后增加以下函数即可。 

@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_UP) {
			if (HorizontalCenterRecyclerView.this.hasFocus()) {
				refreshFocusItemToCenter();
			}
		}	
		return super.dispatchKeyEvent(event);
	}
	
	public void refreshFocusItemToCenter(){
		View tView = ((BaseActivity)getContext()).getCurrentFocus();
		if (tView == null) {
			return;
		}
		int[] Position = new int[2];
		tView.getLocationInWindow(tPosition);
		int tDes = (int) ((this.getX() + this.getWidth()/2) - tView.getWidth() * tView.getScaleX()/2);
		if (tPosition != null && tPosition[0] != tDes) {
			this.smoothScrollBy(tPosition[0] - tDes, 0);
			postInvalidate();
		}
	}

谢谢大家微笑

猜你喜欢

转载自blog.csdn.net/u012591964/article/details/51384721