我在我的应用程序中使用recylerview,每当将新元素添加到recyclerview时,它就会使用滚动到最后一个元素
recyclerView.scrollToPosition(adapter.getCount());
但是,每当键盘打开时(因为editTextView),它会调整视图大小并且recyclerview变小,但无法滚动到最后一个元素.
android:windowSoftInputMode="adjustResize"
我甚至尝试使用以下代码滚动到最后一个元素,但它不起作用
editTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if(hasFocus){ recyclerView.scrollToPosition(chatAdapter.getItemCount()); } } });
我可以尝试adjustPan
将平移向上移动,但它隐藏了我的工具栏.请提出任何解决问题的方法.
您可以使用捕获键盘更改recyclerview.addOnLayoutChangeListener()
.如果bottom小于,oldBottom
则键盘处于up状态.
if ( bottom < oldBottom) { recyclerview.postDelayed(new Runnable() { @Override public void run() { recyclerview.scrollToPosition(bottomPosition); } }, 100); }
添加您的活动或片段:
if (Build.VERSION.SDK_INT >= 11) { recyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { if (bottom < oldBottom) { recyclerView.postDelayed(new Runnable() { @Override public void run() { recyclerView.smoothScrollToPosition( recyclerView.getAdapter().getItemCount() - 1); } }, 100); } } }); }
这个对我有用
LinearLayoutManager layoutManager = new LinearLayoutManager(context); layoutManager.setStackFromEnd(true); recyclerView.setLayoutManager(layoutManager);
虽然这是一个老问题,但我今天遇到了这个问题,并且我发现上述方法都不起作用.这是我的解决方案
recyclerView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { if (bottom < oldBottom) { final int lastAdapterItem = mAdapter.getItemCount() - 1; recyclerView.post(new Runnable() { @Override public void run() { int recyclerViewPositionOffset = -1000000; View bottomView = linearLayoutManager.findViewByPosition(lastAdapterItem); if (bottomView != null) { recyclerViewPositionOffset = 0 - bottomView.getHeight(); } linearLayoutManager.scrollToPositionWithOffset(lastAdapterItem, recyclerViewPositionOffset); } }); } }); }
我发现这postDelayed
是不必要的,并且当回收站滚动到项目中间的某个位置时,使用适配器位置并不能解决问题。我达到了想要的外观:
recycler.addOnLayoutChangeListener((view, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> { if (bottom < oldBottom) { messageRecycler.scrollBy(0, oldBottom - bottom); } })