오늘은 아주 이상한 문제가 있습니다. 나는 리모컨 일부를 가로로 표시하는 RecyclerView가 있는데, 나는 필요한 항목으로 이동하기 위해 smoothScrollToPosition
을 사용하지만 문제가 있음을 알게되었습니다. 마지막 항목으로 스크롤하지 않습니다. 추가 디버깅을 할 때, 나는 나의 recyclerview가 그것보다 더 적은 아이들을 가지고있는 것을 발견했다! 한 번에 3 개씩 5 개의 항목이 표시됩니다. 그러나 아이들 카운트 (recyclerView.getChildCount
)는 5 대신 4를 반환하고, 마지막 아이를 getChildAt(4)
으로 가져올 수 없습니다. 더욱 이상한의 adapter.getItemCount()
수익률 5 및 recyclerView.getAdapter().getItemCount()
돌아 오 ...RecyclerView 어린이 수가 어린이 수보다 작습니다.
layoutAdapter
, recyclerView.getLayoutManager().getItemCount()
반환 (5) 검사에, 그리고`recyclerView..getLayoutManager(). getChildCount()는 4를 반환 ...
두 가지가 필요합니다. : 먼저 마지막 항목으로 스크롤하려면 recyclerView가 필요합니다. 둘째 : 사용자가 항목과 상호 작용할 때 일부 수정을 수행하므로 모든 하위 항목을 가져올 수 있어야합니다.
일부 코드 :
// Scrolling and editing the item inside the recyclerView
// It doesn't scroll to position 4, even having a item there...
mLayoutManager.smoothScrollToPosition(recyclerView, null, position);
// the code bellow returns null if position = 4, even if the recyclerView adapter has a item at index 4, and it is visible...
ImageView iv = (ImageView) recyclerView.getChildAt(position);
if (iv != null) {
iv.setPadding(10, 10, 10, 10);
iv.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
ImageView ivo = (ImageView) recyclerView.getChildAt(position - 1);
if (position - 1 == 0) {
ivo.setPadding(10, 10, 10, 10);
} else {
ivo.setPadding(0, 10, 10, 10);
}
ivo.setBackgroundColor(getResources().getColor(R.color.transparent));
}
smoothScrollToPosition 구현 :
public class SnappingLinearLayoutManager extends LinearLayoutManager {
private static final float MILLISECONDS_PER_INCH = 150f;
public SnappingLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
int position) {
RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext()){
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return new PointF(0, 1);
}
//This returns the milliseconds it takes to scroll one pixel.
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return MILLISECONDS_PER_INCH/displayMetrics.densityDpi;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
private class TopSnappedSmoothScroller extends LinearSmoothScroller {
public TopSnappedSmoothScroller(Context context) {
super(context);
}
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return SnappingLinearLayoutManager.this
.computeScrollVectorForPosition(targetPosition);
}
@Override
protected int getVerticalSnapPreference() {
return SNAP_TO_ANY;
}
}
}
RecycleView가 어댑터의 모든 항목을 보유하지는 않습니다.리사이클 러 뷰리스트의 처음과 끝 부분에 디스플레이 된 뷰의 뷰와 약간의 엑스트라 뷰 만 있으므로 더 빨리 렌더링 할 수 있습니다. 어쩌면 이것이 문제 일 수 있습니다. – Rafal