今日は非常に奇妙な問題があります。私はRecyclerViewに水平にいくつかのサムネイルを表示していますが、私は必要な項目にナビゲートするのにsmoothScrollToPosition
を使用します。最後の項目にスクロールしないでください。さらにデバッグすると、私のリサイクルビューに表示されるものよりも子供が少なくなっています。私は一度に3つずつ、5つの項目を見る。 (recyclerView.getChildCount
を取得した)子供の数は5の代わりに4を返します。最後の子はgetChildAt(4)
で取得できません。さらにより奇妙、adapter.getItemCount()
戻り5、及びrecyclerView.getAdapter().getItemCount()
戻る5 ...RecyclerView子どもの数が子どもの数よりも少ない
、recyclerView.getLayoutManager().getItemCount()
戻る5を検査すると、と `recyclerView..getLayoutManager()のgetChildCount()は4を返し...
私は2つのものが必要です:まず、その最後のアイテムにスクロールするために私のrecyclerViewが必要です。そして、2番目:ユーザーがアイテムとやりとりするときに私はいくつかの変更を行うので、すべての子供を取得する必要があります。
いくつかのコード:
// 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