草庐IT

android - recyclerview 将数据添加到顶部而不会弄乱滚动?

coder 2023-12-16 原文

我正在尝试在回收站 View 的滚动顶部添加一些日期。 这是工作,除了滚动,当添加一些新数据时它会把所有东西都弄乱。

我看到了这个主题:

Link 1

Link 2

但他们都没有解决我的问题。

也许有人可以帮助我...

我使用 volley 获取一些数据,如下所示:

try {
                //Getting json
                json = array.getJSONObject(i);

                //Adding data to the object
                PostObj.setImageUrl(json.getString(Config.TAG_PPIC));
                ...


            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Adding object to the list
            listLf.add(0, PostObj); //0, postobj
        }

        //Notifying the adapter that data has been added or changed
        //adapter.notifyDataSetChanged(); the scroll will jump to position 0
        adapter.notifyItemRangeChanged(0, adapter.getItemCount()); // still not working
    }

我尝试添加 adapter.notifyItemRangeChanged(0, adapter.getItemCount()); 但还是一样。

我也试过:

// Save state
private Parcelable recyclerViewState;
recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();

// Restore state
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);

而且它也不起作用。也许我把它放在了错误的地方或什么的......

我需要一些建议,我做错了什么以及如何获取新数据、通知适配器而不弄乱滚动位置?


编辑-------------------------------- 全类:

public class Comments extends BaseActivity {


    private List<LfGetSet> listLf;

    //Creating Views
    private RecyclerView recyclerView;
    private RecyclerView.LayoutManager layoutManager;
    private RecyclerView.Adapter adapter;

    //Volley Request Queue
    private RequestQueue requestQueue;
    private String requestCount = "0";
    private String lastrequestCount = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ViewGroup content = (ViewGroup) findViewById(R.id.content_frame);
        getLayoutInflater().inflate(R.layout.activity_comments, content, true);

        //Initializing Views
        recyclerView = (RecyclerView) findViewById(R.id.recyclerViewLf);
        recyclerView.setHasFixedSize(true);
        //layoutManager = new LinearLayoutManager(this);

        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setStackFromEnd(true);

        recyclerView.setLayoutManager(layoutManager);

        //Initializing our list
        listLf = new ArrayList<>();
        requestQueue = Volley.newRequestQueue(this);

        //Calling method to get data to fetch data
        getData();

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isLastItemDisplaying(recyclerView)) {
                    getData();
                }
            }
        });

        //initializing our adapter
        adapter = new LfAdapter(listLf, this);

        //Adding adapter to recyclerview
        recyclerView.setAdapter(adapter);


    }

    private JsonArrayRequest getDataFromServer(String requestCount) {
        ...
        return jsonArrayRequest;
    }

    //This method will get data from the web api
    private void getData() {
        //Adding the method to the queue by calling the method getDataFromServer
        requestQueue.add(getDataFromServer(requestCount));
        lastrequestCount = requestCount;
        //Incrementing the request counter
        requestCount++;
    }

    //This method will parse json data
    private void parseData(JSONArray array) {
        for (int i = 0; i < array.length(); i++) {
            //Creating the object
            LfGetSet PostObj = new LfGetSet();
            JSONObject json = null;
            try {
                //Getting json
                json = array.getJSONObject(i);

                //Adding data to the object
                PostObj.setImageUrl(json.getString(Config.TAG_PPIC));
                ...


            } catch (JSONException e) {
                e.printStackTrace();
            }
            //Adding object to the list
            listLf.add(0, PostObj); //0, postobj
        }

        //Notifying the adapter that data has been added or changed
        adapter.notifyDataSetChanged();
    }

    //This method would check that the recyclerview scroll has reached the bottom or not
    private boolean isLastItemDisplaying(RecyclerView recyclerView) {
        if (recyclerView.getAdapter().getItemCount() != 0) {
            int lastVisibleItemPosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
            if (lastVisibleItemPosition != RecyclerView.NO_POSITION
                    && lastVisibleItemPosition == 1
                    && lastrequestCount != requestCount
                    && requestCount != "0")
                return true;
        }
        return false;
    }

}

最佳答案

您可以尝试这种方法,按照正常方式向列表中添加一个新项目,然后更新数组中的数据并将新项目放在顶部。

   // Add a new item the usual way so it goes at the bottom

    int x = 0;

   // Create a new Data list. New item goes 1st

   // Create a Loop

    myList.remove(x); // Remove item from the array at position

    MyList myList = new MyList();

    myList.add(x, theData); // Add data to array at position


    // Now that new data has been inserted to the Array at position X update the List item at that same Position. I usually do this in the Background.

    Handler handler = new Handler();

    final int finalX = x;
    final Runnable r = new Runnable() {
        public void run() {
            adapter.notifyItemChanged(finalX);  // Notify Adapter that the Items data has changed and Update
        }
    };

    handler.post(r);

    x++;

从数据库中读取更新数据然后使用新数据动态更新列表项的代码。但在您的情况下,您需要添加 1 个新项目并使用数组中位置 0 和列表中的新项目数据更新列表。旧项目的位置移动 1。

public void updateStocks() {

        System.out.println("Updating");
        int rec = db.getRecordsCount() - 1;

        List<Records> record = db.getAllRecords();

        int x = 0;

        for (Records cn : record) {

            stocksList.remove(x);

            Livestocks stocks = new Livestocks();

            stocks.setID(cn.getID());
            stocks.setName(cn.getName());
            stocks.setTicker(cn.getTicker());
            stocks.setPrice(cn.getPrice());
            stocks.setOpen(cn.getOpen());
            stocks.setChange(cn.getChange());
            stocks.setPchange(cn.getPchange());
            stocks.setDhigh(cn.getDhigh());
            stocks.setDlow(cn.getDlow());
            stocks.setYhigh(cn.getYhigh());
            stocks.setYlow(cn.getYlow());
            stocks.setVol(cn.getVol());
            stocks.setShares(cn.getShares());
            stocks.setIown(cn.getIown());
            stocks.setMcap(cn.getMcap());
            stocks.setStatus(cn.getStatus());
            stocks.setExchange(cn.getExchange());

            stocksList.add(x, stocks);

            Handler handler = new Handler();

            final int finalX = x;
            final Runnable r = new Runnable() {
                public void run() {
                    adapter.notifyItemChanged(finalX);
                }
            };

            handler.post(r);

            x++;

            if (rec == x) {
            //do nothing
            }
        }

    }

关于android - recyclerview 将数据添加到顶部而不会弄乱滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42916098/

有关android - recyclerview 将数据添加到顶部而不会弄乱滚动?的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  3. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  4. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  5. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  6. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  7. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  8. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  9. ruby - 可以通过多少种方法将方法添加到 ruby​​ 对象? - 2

    当谈到运行时自省(introspection)和动态代码生成时,我认为ruby​​没有任何竞争对手,可能除了一些lisp方言。前几天,我正在做一些代码练习来探索ruby​​的动态功能,我开始想知道如何向现有对象添加方法。以下是我能想到的3种方法:obj=Object.new#addamethoddirectlydefobj.new_method...end#addamethodindirectlywiththesingletonclassclass这只是冰山一角,因为我还没有探索instance_eval、module_eval和define_method的各种组合。是否有在线/离线资

  10. ruby - 如何在 Ruby 中向现有方法定义添加语句 - 2

    我注意到类定义,如果我打开classMyClass,并在不覆盖的情况下添加一些东西我仍然得到了之前定义的原始方法。添加的新语句扩充了现有语句。但是对于方法定义,我仍然想要与类定义相同的行为,但是当我打开defmy_method时似乎,def中的现有语句和end被覆盖了,我需要重写一遍。那么有什么方法可以使方法定义的行为与定义相同,类似于super,但不一定是子类? 最佳答案 我想您正在寻找alias_method:classAalias_method:old_func,:funcdeffuncold_func#similartoca

随机推荐