简体   繁体   English

RecyclerView:添加的项目未显示

[英]RecyclerView : added items not showing

Added items to recyclerView not showing up until user scroll. 添加到recyclerView的项目直到用户滚动才显示。 I'm using websockets to communication. 我正在使用websockets进行通信。 When user on server send message, server returns json which i'm parsing to model and I add it to recyclerview adapter. 当服务器上的用户发送消息时,服务器返回我要解析为模型的json,然后将其添加到recyclerview适配器。 Item is added to recyclerview but it's not showing up until i scroll recyclerview up or down. 项目已添加到recyclerview,但在我向上或向下滚动recyclerview之前它没有显示。 I made a test, where i added static String with test Json and when i click on a button it will trigger the same method but with test data outside websocket and it add item on top of recyclerview. 我做了一个测试,在那里我添加了带有测试Json的静态字符串,当我点击一个按钮时,它将触发相同的方法,但是在websocket外面有测试数据,它会在recyclerview之上添加项目。

Added items with this method are not showing up until user scroll : 使用此方法添加的项目在用户滚动之前不会显示:

WebSocket ws = factory.createSocket("wss://example.com/websocket");
ws.addListener(new WebSocketAdapter() {
            @Override
            public void onTextMessage(WebSocket websocket, String text) throws Exception {
                adapter.add(parseWs(text);
            }
});

private Discussion parseWs(String string) {
    discussion = new JSONObject(string).getJSONObject("data").toString();
    Gson gson = new Gson();
    return gson.fromJson(discussion, Discussion.class);
}

////////////Adapter class////////////
public void add(Discussion disc) {
    list.add(0,disc);
    notifyItemInserted(0);
}

If i add item from clicking on button, items are showing up normally without scrolling : 如果我从点击按钮添加项目,项目正常显示而不滚动:

fab.setOnClickListener(v -> 
    adapter.add(parseWs(test));
    mRecyclerView.scrollToPosition(0);
);

I'm using nv-weboskcet-client java library. 我正在使用nv-weboskcet-client java库。

Not sure what you exactlty want, but try to use 不确定你想要什么,但尝试使用

notifyDataSetChanged();

May this will fix your problem. 愿这可以解决你的问题。

If the call is asynchronous you have to use the Handler class to update your view. 如果调用是异步的,则必须使用Handler类来更新视图。

Android and JavaRx: Android和JavaRx:

https://mttkay.github.io/blog/2013/08/25/functional-reactive-programming-on-android-with-rxjava/ https://mttkay.github.io/blog/2013/08/25/functional-reactive-programming-on-android-with-rxjava/

But just try it with the Handler class. 但只需使用Handler类进行尝试即可。

Handler handler = new Handler();
ws.addListener(new WebSocketAdapter() {
    @Override
    public void onTextMessage(WebSocket websocket, String text) throws Exception {
        handler.post(new Runnable(){
            adapter.add(parseWs(text);
        });
    }
});

Something like that should work :) 这样的东西应该工作:)

May you have to declare Handler handler as a field in your Activity. 您是否必须将Handler处理程序声明为Activity中的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM