繁体   English   中英

在Android中使用socket.io时如何在运行时获取视图?

[英]How to get a view in runtime when using socket.io in android?

我在前端有一个android应用程序,在后端有node js套接字。

我从socket.on事件中获取了聊天中的聊天列表。

此列表中的每个项目都有一个customview,当我收到套接字事件时,需要用不同的值更新此customview。

我怎样才能做到这一点?

这是获取聊天列表时的“我的代码”:

final Handler mHandler04 = new Handler(Looper.getMainLooper());
            mHandler04.post(new Runnable() {
                @Override
                public void run() {
                    SocketManager.getInstance().getSocket().on("allchatres", new Emitter.Listener() {
                        @Override
                        public void call(final Object... args) {
                            g.context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    JSONArray jsonArray = (JSONArray) args[0];
                                    Log.d(TAG, "run: " + jsonArray);
                                        try {
                                            for (int i = 0; i < jsonArray.length(); i++) {
                                                createView(jsonArray.getJSONObject(i).getString("title"), jsonArray.getJSONObject(i).getString("body"));
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                }
                            });
                        }
                    });
                }
            }); 

这是我的Createview代码:

private void createView(final String title, final String body) {
    customViewChat = new customViewChat(g.context);
    layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    customViewChat.txtCsTitle.setText(title);
    customViewChat.txtCsBody.setText(body);
    LinearLayoutItemHolder.addView(customViewChat, layoutParams);
    customViewChat.btnJoin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent(g.context, DetailActivity.class);
            i.putExtra("title", title);
            i.putExtra("body", body);
            startActivity(i);
        }
    });
}

但是当我想像这样更新列表中的customview时:

int count = LinearLayoutItemHolder.getChildCount() ;
Log.d(TAG,"child count : " + count) ;
for(int i = 0 ;i<count ; i++)
{
    View v = LinearLayoutItemHolder.getChildAt(i) ;

}

我在logcat中看到以下结果:

child count : 0

我如何在LinearLayoutItemHolder中获取每个customview?

我想在另一个socket.on事件中更改customView值,但我不能。

我进行了很多搜索,但没有发现任何有用的信息。

任何建议都会有所帮助。

最后,我找到了实现目标的最佳方法:使用RecyclerView!

我在使用自定义视图时有些麻烦,所以我改用了回收站视图。

暂无
暂无

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

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