如何从linearlayout管理器访问新添加的视图

时间:2016-07-11 11:47:31

标签: android android-recyclerview linearlayoutmanager

我正在制作聊天应用程序。 我有一个布局管理器,它扩展了LinearLayoutManager,我想计算添加到适配器的视图的高度,这样当我调用smoothScrollToPosition()时,我可以改变滚动速度。

对于更高的高度,我会将MILLISECONDS_PER_INCH设为较小的值,而对于较小的高度,我会使它变大。

但是我无法计算新添加的视图的高度。

public class SmoothLinearLayoutManager extends LinearLayoutManager {

private ChatAdapter mChatAdapter;
private Context mContext;
private final float MILLISECONDS_PER_INCH = 250f;
public SmoothLinearLayoutManager(Context context,ChatAdapter adapter) {
    super(context);
    mContext = context;
    mChatAdapter = adapter;
}

public SmoothLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
    mContext = context;
}

public SmoothLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    mContext = context;
}

@Override
public void smoothScrollToPosition(final RecyclerView recyclerView, RecyclerView.State state, final int position) {

    Log.d("Scroll",mChatAdapter.getChildHeight()+"");

    LinearSmoothScroller smoothScroller = new LinearSmoothScroller(mContext) {
        @Override
        public PointF computeScrollVectorForPosition(int targetPosition) {
            return SmoothLinearLayoutManager.this.computeScrollVectorForPosition(position);
        }

        @Override
        protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
            return (MILLISECONDS_PER_INCH)/displayMetrics.densityDpi;
        }
    };
    smoothScroller.setTargetPosition(position);
    startSmoothScroll(smoothScroller);
}

}

1 个答案:

答案 0 :(得分:0)

如果您访问新添加的视图的目的是使光滑滚动速度保持恒定,则此库可能对您有用 https://github.com/nshmura/SnappySmoothScroller

像这样:

layoutManager = new SnappyLinearLayoutManager(context);
layoutManager.setSnapDuration(500);
layoutManager.setSeekDuration(1000);