jjzjj

android - 不定式 RecyclerView 对我不起作用

coder 2023-12-16 原文

我知道这个问题以前被问过很多次,但我很困惑为什么有时会加载数据,有时在我到达列表末尾时没有加载数据。此外,当我快速滚动列表时,新数据已加载,但它立即将我返回到列表中的第一项,并从服务器的下一页中删除所有新加载的项目。所以这是第二个问题,第三个问题是当我使用 SwipeRefreshLayout 加载项目时,当我到达列表末尾时我也没有获得新项目。

我已经在我的项目中实现了这个:https://gist.github.com/ssinss/e06f12ef66c51252563e

list.setLayoutManager(manager);
    list.setEmptyView(emptyView);
    list.setItemAnimator(new DefaultItemAnimator());
    list.setAdapter(mAdapter);

    loadJokes(1);

    list.addOnScrollListener(new EndlessRecyclerOnScrollListener(manager) {
        @Override
        public void onLoadMore(final int current_page) {
            loadMoreJokes(current_page);
        }
    });

这是我从服务器加载更多项目的方法:

private void loadMoreJokes(int current_page) {
    StringRequest request = new StringRequest(Request.Method.GET, AppConfig.URL_GET_ALL_JOKES + current_page,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    hideDialog();
                    try {
                        JSONObject object = new JSONObject(response);
                        boolean error = object.getBoolean("error");
                        JSONArray jokes = object.getJSONArray("jokes");
                        if (!error) {
                            for (int i = 0; i < jokes.length(); i++) {
                                JSONObject object1 = jokes.getJSONObject(i);
                                Joke joke = new Joke();
                                joke.setId(object1.optInt("id"));
                                joke.setLikes(object1.optInt("likes"));
                                joke.setComments(object1.optInt("comments"));
                                joke.setJoke(object1.optString("joke"));
                                joke.setCreatedAt(object1.optString("created_at"));
                                joke.setName(object1.optString("user_name"));
                                joke.setImagePath(object1.optString("image_path"));
                                joke.setFacebookUserId(object1.optString("facebook_user_id"));
                                joke.setCategory(object1.optString("category"));
                                mJokes.add(joke);
                            }
                            menu.showMenu(true);
                        }

                        // Notify adapter that data has changed
                        mAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            hideDialog();
            Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

    AppController.getInstance().addToRequestQueue(request);
}

这是我在有人启动应用程序时加载第一个可见项目的方法:

private void loadJokes(int page) {
    pDialog.setMessage("Loading..");
    showDialog();

    StringRequest request = new StringRequest(Request.Method.GET, AppConfig.URL_GET_ALL_JOKES + page,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    mJokes.clear();
                    hideDialog();
                    try {
                        JSONObject object = new JSONObject(response);
                        boolean error = object.getBoolean("error");
                        JSONArray jokes = object.getJSONArray("jokes");
                        if (!error) {
                            for (int i = 0; i < jokes.length(); i++) {
                                JSONObject object1 = jokes.getJSONObject(i);

                                Joke joke = new Joke();
                                joke.setId(object1.optInt("id"));
                                joke.setLikes(object1.optInt("likes"));
                                joke.setComments(object1.optInt("comments"));
                                joke.setJoke(object1.optString("joke"));
                                joke.setCreatedAt(object1.optString("created_at"));
                                joke.setName(object1.optString("user_name"));
                                joke.setImagePath(object1.optString("image_path"));
                                joke.setFacebookUserId(object1.optString("facebook_user_id"));
                                joke.setCategory(object1.optString("category"));
                                mJokes.add(joke);
                            }
                            menu.showMenu(true);
                        }

                        // Notify adapter that data has changed
                        mAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            hideDialog();
            menu.showMenu(true);
            Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

    AppController.getInstance().addToRequestQueue(request);
}

这是 onRefresh() 方法:

@Override
public void onRefresh() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            refreshItems();
        }
    }, 5000);
}

private void refreshItems() {
    loadJokes(1);

    mSwipeRefreshLayout.setRefreshing(false);
}

如果我需要发布更多代码,请告诉我。我真的需要尽快解决这个问题。因此,问题如下:

  • 当快速滚动列表时,正在加载新项目,但之后它立即返回到列表的开头,当我再次转到列表末尾时,加载更多没有响应。

  • 使用 SwipRefreshLayout 刷新列表后,最后滚动也没有响应。

注意:只有当我缓慢浏览列表并且没有滑动刷新列表时,滚动和加载新项目才会起作用。

编辑:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_jokes, container, false);

    mContext = getActivity();
    mView = (CoordinatorLayout) view.findViewById(R.id.coordinatorLayout);

    TextView tvEmptyText = (TextView) view.findViewById(R.id.tv_empty);
    ImageView ivSignal = (ImageView) view.findViewById(R.id.iv_signal);

    if (!ConnectionDetector.getInstance(getActivity()).isOnline() && mAdapter == null) {
        tvEmptyText.setVisibility(View.VISIBLE);
        ivSignal.setVisibility(View.VISIBLE);
        showNoInternetSnackbar();
    }

    // INITIALIZE RECYCLER VIEW
    EmptyRecyclerView list = (EmptyRecyclerView) view.findViewById(R.id.list);
    mJokes = new ArrayList<>();
    mAdapter = new RecyclerJokesAdapter(getActivity(), mJokes, JokesFragment.this, null);

    // Progress dialog
    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Please wait");
    pDialog.setIndeterminate(true);
    pDialog.setCancelable(false);

    showDialog();

    View emptyView = inflater.inflate(R.layout.layout_empty_view, container, false);

    FloatingActionButton fab1 = (FloatingActionButton) view.findViewById(R.id.fab_funny);
    FloatingActionButton fab2 = (FloatingActionButton) view.findViewById(R.id.fab_good_morning);
    FloatingActionButton fab3 = (FloatingActionButton) view.findViewById(R.id.fab_good_night);
    FloatingActionButton fab4 = (FloatingActionButton) view.findViewById(R.id.fab_all);
    menu = (FloatingActionMenu) view.findViewById(R.id.menu_sort_jokes);

    fab1.setOnClickListener(this);
    fab2.setOnClickListener(this);
    fab3.setOnClickListener(this);
    fab4.setOnClickListener(this);

    mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
    mSwipeRefreshLayout.setOnRefreshListener(this);
    mSwipeRefreshLayout.setColorSchemeResources(
            R.color.refresh_progress_1,
            R.color.refresh_progress_2,
            R.color.refresh_progress_3);

    LinearLayoutManager manager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);

    list.setLayoutManager(manager);
    list.setEmptyView(emptyView);
    list.setItemAnimator(new DefaultItemAnimator());
    list.setAdapter(mAdapter);

    if (ConnectionDetector.getInstance(mContext).isOnline()) {
        loadJokes(1);
    } else {
        showNoInternetSnackbar();
        hideDialog();
    }

    list.addOnScrollListener(new EndlessRecyclerOnScrollListener(manager) {
        @Override
        public void onLoadMore(final int current_page) {
            loadMoreJokes(current_page);
        }
    });

    return view;
}

最佳答案

在 onCreate 方法中初始化你的适配器、recyclerView 和 List

List<MyObject> myList = new ArrayList<>();
recyclerViewAdapter = new RecyclerViewAdapter(context, myList)
myRecyclerView.setAdapter(recyclerViewAdapter);

现在,无论何时加载数据。将数据添加到您的 myList 并在您的适配器上调用 notifyDataSetChange

myList.add(data);
recyclerViewAdapter.notifyDataSetChange();

关于android - 不定式 RecyclerView 对我不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36912560/

有关android - 不定式 RecyclerView 对我不起作用的更多相关文章

  1. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  2. 安卓apk修改(Android反编译apk) - 2

    最近因为项目需要,需要将Android手机系统自带的某个系统软件反编译并更改里面某个资源,并重新打包,签名生成新的自定义的apk,下面我来介绍一下我的实现过程。APK修改,分为以下几步:反编译解包,修改,重打包,修改签名等步骤。安卓apk修改准备工作1.系统配置好JavaJDK环境变量2.需要root权限的手机(针对系统自带apk,其他软件免root)3.Auto-Sign签名工具4.apktool工具安卓apk修改开始反编译本文拿Android系统里面的Settings.apk做demo,具体如何将apk获取出来在此就不过多介绍了,直接进入主题:按键win+R输入cmd,打开命令窗口,并将路

  3. ruby-on-rails - "assigns"在 Ruby on Rails 中有什么作用? - 2

    我目前正在尝试学习RubyonRails和测试框架RSpec。assigns在此RSpec测试中做什么?describe"GETindex"doit"assignsallmymodelas@mymodel"domymodel=Factory(:mymodel)get:indexassigns(:mymodels).shouldeq([mymodel])endend 最佳答案 assigns只是检查您在Controller中设置的实例变量的值。这里检查@mymodels。 关于ruby-o

  4. ruby - Ruby 1.9.1 中的 native 线程,对我有什么好处? - 2

    所以,Ruby1.9.1现在是declaredstable.Rails应该与它一起工作,并且正在慢慢地将gem移植到它。它具有native线程和全局解释器锁(GIL)。自从GIL到位后,原生线程是否比1.9.1中的绿色线程有任何优势? 最佳答案 1.9中的线程是原生的,但它们被“放慢了速度”,一次只允许一个线程运行。这是因为如果线程真的并行运行,它会混淆现有代码。优点:IO现在在线程中是异步的。如果一个线程阻塞在IO上,那么另一个线程将继续执行直到IO完成。C扩展可以使用真正的线程。缺点:任何非线程安全的C扩展都可能存在使用Thre

  5. ruby - 字符串文字前面的 * 在 ruby​​ 中有什么作用? - 2

    这段代码似乎创建了一个范围从a到z的数组,但我不明白*的作用。有人可以解释一下吗?[*"a".."z"] 最佳答案 它叫做splatoperator.SplattinganLvalueAmaximumofonelvaluemaybesplattedinwhichcaseitisassignedanArrayconsistingoftheremainingrvaluesthatlackcorrespondinglvalues.Iftherightmostlvalueissplattedthenitconsumesallrvaluesw

  6. ruby - 为什么这个 eval 在 Ruby 中不起作用 - 2

    你能解释一下吗?我想评估来自两个不同来源的值和计算。一个消息来源为我提供了以下信息(以编程方式):'a=2'第二个来源给了我这个表达式来评估:'a+3'这个有效:a=2eval'a+3'这也有效:eval'a=2;a+3'但我真正需要的是这个,但它不起作用:eval'a=2'eval'a+3'我想了解其中的区别,以及如何使最后一个选项起作用。感谢您的帮助。 最佳答案 您可以创建一个Binding,并将相同的绑定(bind)与每个eval相关联调用:1.9.3p194:008>b=binding=>#1.9.3p194:009>eva

  7. ruby-on-rails - Spring 不起作用。 [未初始化常量 Spring::SID::DL] - 2

    我无法运行Spring。这是错误日志。myid-no-MacBook-Pro:myid$spring/Users/myid/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/spring-0.0.10/lib/spring/sid.rb:17:in`fiddle_func':uninitializedconstantSpring::SID::DL(NameError)from/Users/myid/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/spring-0.0.10/li

  8. ruby-on-rails - Simple_form 必填字段不起作用 - Ruby on Rails - 2

    我在RoR应用程序中有一个提交表单,是使用simple_form构建的。当字段为空白时,应用程序仍会继续下一步,而不会提示错误或警告。默认情况下,这些字段应该是required:true;但即使手动编写也行不通。该应用有3个步骤:NewPost(新View)->Preview(创建View)->Post。我的Controller和View的摘录会更清楚:defnew@post=Post.newenddefcreate@post=Post.new(params.require(:post).permit(:title,:category_id))ifparams[:previewButt

  9. ruby-on-rails - Heroku Action 缓存似乎不起作用 - 2

    我一直在Heroku上尝试不同的缓存策略,并添加了他们的memcached附加组件,目的是为我的应用程序添加Action缓存。但是,当我在我当前的应用程序上查看Rails.cache.stats时(安装了memcached并使用dalligem),在执行应该缓存的操作后,我得到current和total_items为0。在Controller的顶部,我想缓存我有的Action:caches_action:show此外,我修改了我的环境配置(对于在Heroku上运行的配置)config.cache_store=:dalli_store我是否可以查看其他一些统计数据,看看它是否有效或我做错

  10. ruby-on-rails - Rake 预览在 Octopress 中不起作用 - 2

    我在我的机器上安装了ruby​​版本1.9.3,并且正在为我的个人网站开发一个octopress项目。我为我的gems使用了rvm,并遵循了octopress.org记录的所有步骤。但是我在我的rake服务器中发现了一些错误。这是我的命令日志。Tin-Aung-Linn:octopresstal$ruby--versionruby1.9.3p448(2013-06-27revision41675)[x86_64-darwin12.4.0]Tin-Aung-Linn:octopresstal$rakegenerate##GeneratingSitewithJekyllidenticals

随机推荐