簡體   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