我已经使用 Recycler View 成功实现了无限滚动。我正在使用 this代码,这很完美,但以下情况除外
情况 1:当列表有 2 个小于屏幕尺寸的项目时,它看起来像 OnLoadMore 再次调用,因为它发现自己到达列表的末尾
我在做什么:我从 1 个 fragment 获取列表,然后将此列表发送到另一个 fragment ,在该 fragment 中有一个带有 onScroll listner 的 RecyclerView,如下所示:
recyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount) {
// do something...
currentVisiblePosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
pageNumber = pageNumber + 1;
CallingMyApi();
}
});
困惑:
所以我可以猜测这是由于 ListView 中的项目较少导致的问题如何控制请帮助我??
更新一:我的 fragment 代码
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mAdapter = new EnrollmentSearchAdapter(getActivity(), parentList);
rvSearchEnrollments.addOnScrollListener(new EndlessRecyclerOnScrollListener(mLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount) {
// do something...
if(parentList!=null && parentList.size()>3) { // just checking my own that 3 items should not be minimum to screen size , where as here it should be more flexible solution
currentVisiblePosition = ((LinearLayoutManager) rvSearchEnrollments.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
pageNumber = pageNumber + 1;
SearchSundaySchoolParentsCouples searchSundaySchoolParentsCouples = new SearchSundaySchoolParentsCouples(keyword, 20, pageNumber, getActivity());
searchSundaySchoolParentsCouples.execute();
}
}
});
rvSearchEnrollments.addItemDecoration(new SimpleDividerItemDecoration(getActivity()));
rvSearchEnrollments.setAdapter(mAdapter);
}
最佳答案
使用 EndlessRecyclerViewScrollListener OnScrollListener 子类(来自流行的 Gist)。当列表中的项目最小然后屏幕大小时,您需要更改一些内容才能使无休止的滚动 RecyclerView 正常工作。
这是您需要添加到 EndlessRecyclerViewScrollListener 的内容类:
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState)
{
super.onScrollStateChanged(recyclerView, newState);
// Don't do any work until after the ScrollEvent has ended, so do the following check.
if (newState == RecyclerView.SCROLL_STATE_IDLE)
{
// supply a positive number to recyclerView.canScrollVertically(int direction) to check if scrolling down.
boolean canScrollDownMore = recyclerView.canScrollVertically(1);
// If recyclerView.canScrollVertically(1) returns false it means you're at the end of the list.
if (!canScrollDownMore)
{
//call the overridden onScrolled() method in our EndlessRecyclerViewScrollListener class.
// supply any positive number to the third argument to indicate that we've scrolled downward.
onScrolled(recyclerView, 0, 1);
}
}
}
说明: 我们需要实现 onScrollStateChanged() 方法,因为 onScrolled() 在结束时不会被调用列表,或者至少当列表中的项目小于屏幕大小时它不会被调用。
这是包含您需要的更新的整个 EndlessRecyclerViewScrollListener 类:
public abstract class EndlessRecyclerViewScrollListener extends RecyclerView.OnScrollListener
{
// The minimum amount of items to have below your current scroll position
// before loading more.
private int visibleThreshold = 5;
// The current offset index of data you have loaded
private int currentPage = 0;
// The total number of items in the dataset after the last load
private int previousTotalItemCount = 0;
// True if we are still waiting for the last set of data to load.
private boolean loading = true;
// Sets the starting page index
private int startingPageIndex = 0;
private RecyclerView.LayoutManager layoutManager;
public void setLayoutManager(RecyclerView.LayoutManager layoutManager)
{
this.layoutManager = layoutManager;
}
public RecyclerView.LayoutManager getLayoutManager()
{
return layoutManager;
}
public EndlessRecyclerViewScrollListener(LinearLayoutManager layoutManager)
{
this.layoutManager = layoutManager;
}
public EndlessRecyclerViewScrollListener(GridLayoutManager layoutManager, int visibleThreshold)
{
this.layoutManager = layoutManager;
this.visibleThreshold = visibleThreshold * layoutManager.getSpanCount();
}
public EndlessRecyclerViewScrollListener(
StaggeredGridLayoutManager layoutManager,
int visibleThreshold)
{
this.layoutManager = layoutManager;
this.visibleThreshold = visibleThreshold * layoutManager.getSpanCount();
}
public int getLastVisibleItem(int[] lastVisibleItemPositions)
{
int maxSize = 0;
for (int i = 0; i < lastVisibleItemPositions.length; i++)
{
if (i == 0)
{
maxSize = lastVisibleItemPositions[i];
}
else if (lastVisibleItemPositions[i] > maxSize)
{
maxSize = lastVisibleItemPositions[i];
}
}
return maxSize;
}
// This happens many times a second during a scroll, so be wary of the code you place here.
// We are given a few useful parameters to help us work out if we need to load some more data,
// but first we check if we are waiting for the previous load to finish.
@Override
public void onScrolled(RecyclerView view, int dx, int dy)
{
if (dy < 1)
{
// don't do anything when scrolling up.
return;
}
int lastVisibleItemPosition = 0;
int totalItemCount = layoutManager.getItemCount();
if (layoutManager instanceof StaggeredGridLayoutManager)
{
int[] lastVisibleItemPositions = ((StaggeredGridLayoutManager) layoutManager).findLastVisibleItemPositions(null);
// get maximum element within the list
lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions);
}
else if (layoutManager instanceof GridLayoutManager)
{
lastVisibleItemPosition = ((GridLayoutManager) layoutManager).findLastVisibleItemPosition();
}
else if (layoutManager instanceof LinearLayoutManager)
{
lastVisibleItemPosition = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
}
// If the total item count is zero and the previous isn't, assume the
// list is invalidated and should be reset back to initial state
if (totalItemCount < previousTotalItemCount)
{
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = totalItemCount;
if (totalItemCount == 0)
{
this.loading = true;
}
}
// If it’s still loading, we check to see if the dataset count has
// changed, if so we conclude it has finished loading and update the current page
// number and total item count.
if (loading && (totalItemCount >= previousTotalItemCount))
{
loading = false;
previousTotalItemCount = totalItemCount;
}
// If it isn’t currently loading, we check to see if we have breached
// the visibleThreshold and need to reload more data.
// If we do need to reload some more data, we execute onLoadMore to fetch the data.
// threshold should reflect how many total columns there are too
if (!loading && (lastVisibleItemPosition + visibleThreshold) > totalItemCount)
{
currentPage++;
onLoadMore(currentPage, totalItemCount, view);
loading = true;
}
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState)
{
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE)
{
// supply a positive number to recyclerView.canScrollVertically(int direction) to check if scrolling down.
boolean canScrollDownMore = recyclerView.canScrollVertically(1);
// If recyclerView.canScrollVertically(1) returns false it means you're at the end of the list.
if (!canScrollDownMore)
{
onScrolled(recyclerView, 0, 1);
}
}
}
// Call this method whenever performing new searches on in onRefresh() if using SwipeRefresh
public void resetState()
{
this.currentPage = this.startingPageIndex;
this.previousTotalItemCount = 0;
this.loading = true;
}
// Defines the process for actually loading more data based on page
public abstract void onLoadMore(int page, int totalItemsCount, RecyclerView view);
}
用法简要示例: ( more info here )
public class MainActivity extends Activity {
// Store a member variable for the listener
private EndlessRecyclerViewScrollListener scrollListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Configure the RecyclerView
RecyclerView rvItems = (RecyclerView) findViewById(R.id.rvContacts);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rvItems.setLayoutManager(linearLayoutManager);
// Retain an instance so that you can call `resetState()` for fresh searches
scrollListener = new EndlessRecyclerViewScrollListener(linearLayoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
loadNextDataFromApi(page);
}
};
// Adds the scroll listener to RecyclerView
rvItems.addOnScrollListener(scrollListener);
}
// Append the next page of data into the adapter
// This method probably sends out a network request and appends new data items to your adapter.
public void loadNextDataFromApi(int offset) {
// Send an API request to retrieve appropriate paginated data
// --> Send the request including an offset value (i.e `page`) as a query parameter.
// --> Deserialize and construct new model objects from the API response
// --> Append the new data objects to the existing set of items inside the array of items
// --> Notify the adapter of the new items made with `notifyItemRangeInserted()`
}
}
您可能需要稍微修改一下才能使其在您的场景中正常工作,但提供的代码是一个很好的起点。
关于android - 当列表中的项目最小然后屏幕大小时,无尽滚动 RecyclerView 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39077218/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr