Cocos2d-x 手遊聊天系統Demo實現(Lua實現)

https://blog.csdn.net/wwj_748/article/details/38414009

Cocos2d-x 手遊聊天系統Demo實現

 轉載請註明:IT_xiao小巫

   本篇博客給大家分享的是一個手遊聊天系統,筆者也是第一次使用Cocos2d-x來實現這樣一個模塊,其中有很多不清楚不明白的地方都是通過自己不斷摸索實現的,前面筆者對聊天系統做的簡單的需求分析,只是對聊天的一些元素進行的說明還不太夠專業。本篇博客會給大家介紹如何實現一個手遊聊天Demo,會從代碼層面上給大家做相關的說明,如有不對或者錯漏的地方請各位明確指出並糾正。


首先來給大家看一下動態效果圖:



本篇博客內容大綱:

1. 加載Cocostudio製作的UI

2. Button的觸摸事件監聽

3. ListView添加列表項並設置列表點擊事件

4. 富文本實現(可顯示顏色文字和圖片、動畫)

5. 文本輸入框實現(解決pc鍵盤無法刪除字符的bug)

6. 動態往ListView添加列表項



一、加載Cocostudio製作的UI

  筆者所分享的這個Demo是通過Cocostudio的UI編輯器製作的,童鞋們也可自己製作更加好看的UI,不過一般都會有美工幫我們做好讓我使用的。如下圖所示:



  UI製作完之後,導出項目,然後把資源複製到我們項目的res目錄下,筆者這裏是把ChatUI_1複製到了res下,然後我們使用Lua代碼實現加載json文件到我們的程序中去:

[javascript] view plain copy
  1. ChatScene.widget = ccs.GUIReader:getInstance():widgetFromJsonFile( "ChatUI_1/ChatUI_1.json" )  

我們在編輯器添加了多個對象:

WorldPanel、PartyPanel、ChatPanel分別對應世界、公會、私聊三個板塊,板塊下面對應其相應的子節點:WordList、PartyList、ChatList。

我們需要在程序中找到它們:

[javascript] view plain copy
  1. --[[  
  2. ============================  
  3. findViews()  
  4. 找到UI控件  
  5. ============================  
  6. ]]--  
  7. function ChatScene.findViews()  
  8.     ChatScene.widget = ccs.GUIReader:getInstance():widgetFromJsonFile( "ChatUI_1/ChatUI_1.json" )  
  9.     ChatScene.widget:setPosition( cc.p( 40, 40 ) )  
  10.   
  11.     loadListViewItemFromJson()  
  12.     -- 獲得UI界面上的3個按鈕  
  13.     worldButton = ChatScene.widget:getChildByTag(6)  
  14.     partyButton = ChatScene.widget:getChildByTag(7)  
  15.     chatButton = ChatScene.widget:getChildByTag(8)  
  16.   
  17.     -- 獲得三個每個按鈕對應的三個面板  
  18.     wordPanel = ChatScene.widget:getChildByTag(5)  
  19.     partyPanel = ChatScene.widget:getChildByTag(9)  
  20.     chatPanel = ChatScene.widget:getChildByTag(10)  
  21.   
  22.     -- 獲得每個面板的ListView  
  23.     worldList = wordPanel:getChildByTag(13)  
  24.     partyList = partyPanel:getChildByTag(14)  
  25.     chatList = chatPanel:getChildByTag(15)  
  26.   
  27.     -- 獲得輸入框  
  28.     inputBox = ChatScene.widget:getChildByTag(11)  
  29.     sendButton = ChatScene.widget:getChildByTag(12)  
  30.   
  31.     dialog = ChatScene.widget:getChildByTag(20)  
  32.     chat = dialog:getChildByTag(21)  
  33.     lahei = dialog:getChildByTag(22)  
  34.     closeButton = dialog:getChildByTag(27)  
  35. end  

  每個UI對象有相應的Tag屬性,我們可以通過找到其父節點,然後調用getChildByTag傳進tag的值找到控件。只有找到這些控件,我們才能去使用它。


二、Button的觸摸事件監聽

  筆者這個demo,通過監聽“世界”、“公會”、“私聊”三個按鈕來分別切換不同的板塊,按鈕的觸摸監聽事件很簡單:

[javascript] view plain copy
  1. -- 設置按鈕監聽事件  
  2.    worldButton:addTouchEventListener(touchEvent)  
  3.    partyButton:addTouchEventListener(touchEvent)  
  4.    chatButton:addTouchEventListener(touchEvent)  

[javascript] view plain copy
  1. --[[  
  2. touchEvent  
  3. 觸摸事件回調方法  
  4. ]]--  
  5. local function touchEvent( sender, eventType )  
  6.     if sender:getTag() == TAG_WORLD_BUTTON then  
  7.         wordPanel:setVisible(true)  
  8.         partyPanel:setVisible(false)  
  9.         chatPanel:setVisible(false)  
  10.         dialog:setVisible(false)  
  11.         ChatScene.setCurrentTag( TAG_WORLD )  
  12.     elseif sender:getTag() == TAG_PARTY_BUTTON then  
  13.         partyPanel:setVisible(true)  
  14.         wordPanel:setVisible(false)  
  15.         chatPanel:setVisible(false)  
  16.         dialog:setVisible(false)  
  17.         ChatScene.setCurrentTag( TAG_PARTY )  
  18.     elseif sender:getTag() == TAG_CHAT_BUTTON then  
  19.         partyPanel:setVisible(false)  
  20.         wordPanel:setVisible(false)  
  21.         chatPanel:setVisible(true)  
  22.         dialog:setVisible(false)  
  23.         ChatScene.setCurrentTag( TAG_CHAT )  
  24.   
  25. end  

以上面這種方式就可以實現切換三個板塊了。


三、ListView添加列表項並設置列表點擊事件

 我們可以看到效果圖裏面每個板塊下面有對應的列表,它是使用Cocos2d-x UI中的ListView所呈現的。

 筆者感覺使用ListView比較麻煩,這裏筆者給出相應的使用方法供大家參考:

--首先我們爲ListView提供三組數據

[javascript] view plain copy
  1. -- 初始化三組數據  
  2.    local array = {}  
  3.    for i = 1, 20 do  
  4.        array[i] = string.format("請叫我巫大大%d", i - 1)  
  5.    end  
  6.   
  7.    local array1 = {}  
  8.    for i = 1, 20 do  
  9.        array1[i] = string.format("公會開放啦%d", i - 1 )  
  10.    end  
  11.   
  12.    local array2 = {}  
  13.    for i = 1, 20 do  
  14.        array2[i] = string.format("私聊列表項%d", i - 1 )  
  15.    end  

--設置默認模型

[javascript] view plain copy
  1. -- 創建模型  
  2. local default_button = ccui.Button:create("cocosui/backtotoppressed.png""cocosui/backtotopnormal.png")  
  3. default_button:setName("Title Button")  
  4.   
  5. -- 創建默認item  
  6. local default_itme = ccui.Layout:create()  
  7. default_itme:setTouchEnabled(true)  
  8. default_itme:setContentSize(default_button:getContentSize())  
  9. default_button:setPosition(cc.p( default_itme:getContentSize().width / 2.0, default_itme:getContentSize().height / 2.0 ))  
  10. default_itme:addChild(default_button)  
  11.   
  12. -- 設置模型  
  13. worldList:setItemModel(default_itme)  

--添加自定義項

[javascript] view plain copy
  1. -- 獲得數組的大小  
  2.     local count = table.getn(array)  
  3.     print("count:"..count)  
  4.     -- 添加自定義item  
  5.     for i = 1, count do  
  6.         -- 創建一個Button  
  7.         local custom_button = ccui.Button:create("cocosui/button.png""cocosui/buttonHighlighted.png")  
  8.         -- 設置Button名字  
  9.         custom_button:setName("Title Button")  
  10.         --  設置按鈕使用九宮(scale9)渲染器進行渲染  
  11.         custom_button:setScale9Enabled(true)  
  12.         -- 設置內容尺寸  
  13.         custom_button:setContentSize(default_button:getContentSize())  
  14.   
  15.         -- 創建一個佈局  
  16.         local custom_item = ccui.Layout:create()  
  17.         -- 設置內容大小  
  18.         custom_item:setContentSize(custom_button:getContentSize())  
  19.         -- 設置位置  
  20.         custom_button:setPosition(cc.p(custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0))  
  21.         -- 往佈局中添加一個按鈕  
  22.         custom_item:addChild(custom_button)  
  23.         -- 往ListView中添加一個佈局  
  24.         worldList:addChild(custom_item)  
  25.   
  26.     end  

--每一項數據

[javascript] view plain copy
  1. -- 設置item data  
  2.    items_count = table.getn(worldList:getItems())  
  3.    for i = 1, items_count do  
  4.        -- 返回一個索引和參數相同的項.  
  5.        local item = worldList:getItem( i - 1 )  
  6.        local button = item:getChildByName("Title Button")  
  7.        local index = worldList:getIndex(item)  
  8.        button:setTitleText(array[index + 1])  
  9.    end  

--設置ListView的點擊事件和滾動事件

[javascript] view plain copy
  1. -- 設置ListView的監聽事件  
  2. worldList:addScrollViewEventListener(scrollViewEvent)  
  3. worldList:addEventListener(listViewEvent)  

[javascript] view plain copy
  1. -- ListView點擊事件回調  
  2. local function listViewEvent(sender, eventType)  
  3.     -- 事件類型爲點擊結束  
  4.     if eventType == ccui.ListViewEventType.ONSELECTEDITEM_END then  
  5.         print("select child index = ",sender:getCurSelectedIndex())  
  6.         if dialog:isVisible() == true then  
  7.             dialog:setVisible(false)  
  8.         else  
  9.             ChatScene.showDialog()  
  10.         end  
  11.     end  
  12. end  
  13.   
  14. -- 滾動事件方法回調  
  15. local function scrollViewEvent(sender, eventType)  
  16.     -- 滾動到底部  
  17.     if eventType == ccui.ScrollviewEventType.scrollToBottom then  
  18.         print("SCROLL_TO_BOTTOM")  
  19.         -- 滾動到頂部  
  20.     elseif eventType == ccui.ScrollviewEventType.scrollToTop then  
  21.         print("SCROLL_TO_TOP")  
  22.     end  
  23.   
  24. end  

四、 富文本實現(可顯示顏色文字和圖片、動畫)

   何爲富文本?筆者的理解是有着豐富文本的展示方式,比如可以展示顏色文本、圖片、動畫、還有超鏈接的這種就叫富文本。以前舊的版本Cocos2d-x可能並未提供這方面的支持,至於是哪個版本支持的筆者也沒有去深究,筆者這裏使用版本是Cocos2d-x 3.2,它就提供了類似富文本的類,滿足基本的需求。



代碼實現:

[javascript] view plain copy
  1. --[[  
  2. ==================  
  3. RichText  
  4. 富文本  
  5. =================  
  6. ]]--  
  7. function ChatScene.RichText()  
  8.     local richText = ccui.RichText:create()  
  9.     richText:ignoreContentAdaptWithSize(false)  
  10.     richText:setContentSize(cc.size(100, 100))  
  11.   
  12.     local re1 = ccui.RichElementText:create( 1, cc.c3b(255, 255, 255), 255, "This color is white. ""Helvetica", 10 )  
  13.     local re2 = ccui.RichElementText:create( 2, cc.c3b(255, 255,   0), 255, "And this is yellow. ""Helvetica", 10 )  
  14.     local re3 = ccui.RichElementText:create( 3, cc.c3b(0,   0, 255), 255, "This one is blue. ""Helvetica", 10 )  
  15.     local re4 = ccui.RichElementText:create( 4, cc.c3b(0, 255,   0), 255, "And green. ""Helvetica", 10 )  
  16.     local re5 = ccui.RichElementText:create( 5, cc.c3b(255,  0,   0), 255, "Last one is red ""Helvetica", 10 )  
  17.   
  18.     local reimg = ccui.RichElementImage:create( 6, cc.c3b(255, 255, 255), 255, "cocosui/sliderballnormal.png" )  
  19.   
  20.     -- 添加ArmatureFileInfo, 由ArmatureDataManager管理  
  21.     ccs.ArmatureDataManager:getInstance():addArmatureFileInfo( "cocosui/100/100.ExportJson" )  
  22.     local arr = ccs.Armature:create( "100" )  
  23.     arr:getAnimation():play( "Animation1" )  
  24.   
  25.     local recustom = ccui.RichElementCustomNode:create( 1, cc.c3b(255, 255, 255), 255, arr )  
  26.     local re6 = ccui.RichElementText:create( 7, cc.c3b(255, 127,   0), 255, "Have fun!! ""Helvetica", 10 )  
  27.     richText:pushBackElement(re1)  
  28.     richText:insertElement(re2, 1)  
  29.     richText:pushBackElement(re3)  
  30.     richText:pushBackElement(re4)  
  31.     richText:pushBackElement(re5)  
  32.     richText:insertElement(reimg, 2)  
  33.     richText:pushBackElement(recustom)  
  34.     richText:pushBackElement(re6)  
  35.   
  36.     richText:setLocalZOrder(10)  
  37.   
  38.     return richText  
  39. end  

五、文本輸入框實現(解決pc鍵盤無法刪除字符的bug)

  CocostudioUI編輯器提供TextField(輸入框),筆者在這裏也對它進行了實現,聊天系統一般需要玩家輸入信息,所以這裏提供了一個輸入框。但筆者在使用這個UI的時候,發現在win32平臺不能對輸入的文本進行刪除,但在移動設備可以使用輸入法對它進行編輯,所以筆者在這裏做了相關的處理把這個bug修正了。

[javascript] view plain copy
  1. --- 鍵盤事件監聽回調方法  
  2.    local function onkeyPressed(keycode, event)  
  3.        print("keypress")  
  4.        if keycode == cc.KeyCode.KEY_BACKSPACE then  
  5.           local str = inputBox:getStringValue()  
  6.            str = string.sub( str, 0, string.len( str ) - 1 )  
  7.            inputBox:setText( str )          
  8.        end  
  9.    end  
  10.      
  11.    -- 鍵盤監聽事件  
  12.    local keyListener = cc.EventListenerKeyboard:create()  
  13.    keyListener:registerScriptHandler(onkeyPressed,cc.Handler.EVENT_KEYBOARD_PRESSED)  
  14.    local eventDispatcher = ChatScene.uiLayer:getEventDispatcher()  
  15.    eventDispatcher:addEventListenerWithSceneGraphPriority(keyListener, ChatScene.uiLayer)  

通過以上方式,我們就可以使用簡拼的BackSpace對字符進行刪除了。大家請叫我活雷鋒。


六、動態往ListView添加列表項

  筆者想到聊天系統的列表是不斷刷新的,所以可能需要實現動態添加列表項,其實這個實現很簡單的,只需要在代碼中監聽相應的事件,然後往ListView添加一項就可以了。

這裏我監聽了發送按鈕的點擊事件,然後獲取到輸入框的文本,在把文本添加到列表項中去。

[javascript] view plain copy
  1. if sender:getTag() == TAG_SEND_BUTTON then  
  2.         print("sendText...")  
  3.         -- 獲得輸入框的文本  
  4.         local value = inputBox:getStringValue()  
  5.         local textView = ccui.Text:create(value,"Arial",20)  
  6.         print("value:"..value)  
  7.         if eventType == ccui.TouchEventType.began then  
  8. --            local custom_text = ChatScene.RichText()  
  9.             local custom_item = ccui.Layout:create()  
  10.             custom_item:setContentSize( textView:getContentSize() )  
  11.             textView:setPosition( cc.p( custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0 ) )  
  12.             custom_item:addChild( textView )  
  13.             -- 如果當前Tag爲世界  
  14.             if ChatScene.getCurrentTag() == TAG_WORLD then  
  15.                 -- 插入自定義項  
  16.                 worldList:insertCustomItem( custom_item, 0 )  
  17.                 --                worldList:addChild(custom_item)  
  18.             elseif ChatScene.getCurrentTag() == TAG_PARTY then  
  19.                 --                partyList:addChild(custom_item)  
  20.                 partyList:insertCustomItem( custom_item, 0 )  
  21.             elseif ChatScene.getCurrentTag() == TAG_CHAT then  
  22.                 --                chatList:addChild(custom_item)  
  23.                 chatList:insertCustomItem( custom_item, 0 )  
  24.             end  
  25.         end  


以上基本是筆者這個聊天系統的重要內容,下面把完整的實現代碼給大家:

[javascript] view plain copy
  1. --[[  
  2. ===============  
  3. ChatSence  
  4. 聊天系統模塊  
  5. ===============  
  6. ]]--  
  7.   
  8. -- 類  
  9. local ChatScene = {}  
  10. ChatScene.uiLayer = nil  
  11. ChatScene.widget = nil  
  12.   
  13. -- 窗口大小  
  14. local winSize = nil  
  15.   
  16. -- 獲得UI界面上的3個按鈕  
  17. local worldButton = nil  
  18. local partyButton = nil  
  19. local chatButton = nil  
  20.   
  21. -- 獲得三個每個按鈕對應的三個面板  
  22. local wordPanel = nil  
  23. local partyPanel = nil  
  24. local chatPanel = nil  
  25.   
  26. -- 獲得每個面板的ListView  
  27. local worldList = nil  
  28. local partyList = nil  
  29. local chatList = nil  
  30.   
  31. -- 列表項  
  32. local listview_item = nil  
  33. local head_icon = nil  
  34. local level = nil  
  35. local name = nil  
  36. local text = nil  
  37.   
  38. -- 列表項個數  
  39. local items_count = nil  
  40.   
  41. -- 獲得輸入框  
  42. local inputBox = nil  
  43. local sendButton = nil  
  44.   
  45. -- 彈出對話框  
  46. local dialog = nil  
  47. local chat = nil  
  48. local lahei = nil  
  49. local closeButton = nil  
  50.   
  51. -- 三個標記  
  52. local flag = nil  
  53. local TAG_WORLD = 1 -- 標識世界  
  54. local TAG_PARTY = 2 -- 標識公會  
  55. local TAG_CHAT = 3 -- 標識私聊  
  56.   
  57. -- 一些按鈕的Tag  
  58. local TAG_WORLD_BUTTON = 1  
  59. local TAG_PARTY_BUTTON = 2  
  60. local TAG_CHAT_BUTTON = 3  
  61. local TAG_SEND_BUTTON = 4  
  62. local TAG_CHAT_BUTTON2 = 5  
  63. local TAG_LAHEI_BUTTON = 6  
  64. local TAG_CLOSE_BUTTON = 7  
  65.   
  66. -- 場景創建  
  67. ChatScene.create = function()  
  68.     local scene = cc.Scene:create()  
  69.     scene:addChild( ChatScene.createChatLayer() )  
  70.     return scene  
  71. end  
  72.   
  73. --[[  
  74. touchEvent  
  75. 觸摸事件回調方法  
  76. ]]--  
  77. local function touchEvent( sender, eventType )  
  78.     if sender:getTag() == TAG_WORLD_BUTTON then  
  79.         wordPanel:setVisible(true)  
  80.         partyPanel:setVisible(false)  
  81.         chatPanel:setVisible(false)  
  82.         dialog:setVisible(false)  
  83.         ChatScene.setCurrentTag( TAG_WORLD )  
  84.     elseif sender:getTag() == TAG_PARTY_BUTTON then  
  85.         partyPanel:setVisible(true)  
  86.         wordPanel:setVisible(false)  
  87.         chatPanel:setVisible(false)  
  88.         dialog:setVisible(false)  
  89.         ChatScene.setCurrentTag( TAG_PARTY )  
  90.     elseif sender:getTag() == TAG_CHAT_BUTTON then  
  91.         partyPanel:setVisible(false)  
  92.         wordPanel:setVisible(false)  
  93.         chatPanel:setVisible(true)  
  94.         dialog:setVisible(false)  
  95.         ChatScene.setCurrentTag( TAG_CHAT )  
  96.     elseif sender:getTag() == TAG_SEND_BUTTON then  
  97.         print("sendText...")  
  98.         -- 獲得輸入框的文本  
  99.         local value = inputBox:getStringValue()  
  100.         local textView = ccui.Text:create(value,"Arial",20)  
  101.         print("value:"..value)  
  102.         if eventType == ccui.TouchEventType.began then  
  103. --            local custom_text = ChatScene.RichText()  
  104.             local custom_item = ccui.Layout:create()  
  105.             custom_item:setContentSize( textView:getContentSize() )  
  106.             textView:setPosition( cc.p( custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0 ) )  
  107.             custom_item:addChild( textView )  
  108.             -- 如果當前Tag爲世界  
  109.             if ChatScene.getCurrentTag() == TAG_WORLD then  
  110.                 -- 插入自定義項  
  111.                 worldList:insertCustomItem( custom_item, 0 )  
  112.                 --                worldList:addChild(custom_item)  
  113.             elseif ChatScene.getCurrentTag() == TAG_PARTY then  
  114.                 --                partyList:addChild(custom_item)  
  115.                 partyList:insertCustomItem( custom_item, 0 )  
  116.             elseif ChatScene.getCurrentTag() == TAG_CHAT then  
  117.                 --                chatList:addChild(custom_item)  
  118.                 chatList:insertCustomItem( custom_item, 0 )  
  119.             end  
  120.         end  
  121.     elseif sender:getTag() == TAG_CHAT_BUTTON2 then  
  122.         partyPanel:setVisible(false)  
  123.         wordPanel:setVisible(false)  
  124.         chatPanel:setVisible(true)  
  125.         dialog:setVisible(false)  
  126.     elseif sender:getTag() == TAG_LAHEI_BUTTON then  
  127.         print("我就把你拉黑,逗比")  
  128.     elseif sender:getTag() == TAG_CLOSE_BUTTON then  
  129.         dialog:setVisible(false)  
  130.     elseif sender:getTag() == 8 then  
  131.         if eventType == ccui.TouchEventType.ended then  
  132.             ChatScene.widget:setVisible( not ChatScene.widget:isVisible() )  
  133.         end  
  134.     end  
  135. end  
  136.   
  137. local function onExit(strEventName)  
  138.     ChatScene.uiLayer:release()  
  139.     ChatScene.uiLayer = nil  
  140. end  
  141.   
  142. --[[  
  143. =================  
  144. addOpenButton  
  145. 添加一個打開的按鈕  
  146. =================  
  147. ]]--  
  148. function ChatScene.addOpenButton()  
  149.     local openButton = ccui.Button:create() -- 創建一個按鈕  
  150.     openButton:setTouchEnabled(true)-- 設置可觸摸  
  151.     openButton:loadTextures( "cocosui/animationbuttonnormal.png""cocosui/animationbuttonpressed.png""" )--加載紋理  
  152.     openButton:setAnchorPoint( cc.p( 0, 0 ) )  
  153.     openButton:setPosition( cc.p( winSize.width -100, winSize.height - 50 ) )  
  154.     ChatScene.uiLayer:addChild(openButton, 1)  
  155.     openButton:setTag(8)  
  156.     openButton:addTouchEventListener(touchEvent)  
  157. end  
  158.   
  159. --[[  
  160. ==============  
  161. textFieldEvent  
  162. 輸入框監聽事件回調方法  
  163. ==============  
  164. ]]--  
  165. local function textFieldEvent(sender, eventType)  
  166.     if eventType == ccui.TextFiledEventType.attach_with_ime then  
  167.         print("attach_with_ime")  
  168.     elseif eventType == ccui.TextFiledEventType.detach_with_ime then  
  169.         print("detach_with_ime")  
  170.     elseif eventType == ccui.TextFiledEventType.insert_text then  
  171.         print("insert_text")  
  172.     elseif eventType == ccui.TextFiledEventType.delete_backward then  
  173.         print("delete_backward")  
  174.   
  175.     end  
  176. end  
  177.   
  178.   
  179. -- ListView點擊事件回調  
  180. local function listViewEvent(sender, eventType)  
  181.     -- 事件類型爲點擊結束  
  182.     if eventType == ccui.ListViewEventType.ONSELECTEDITEM_END then  
  183.         print("select child index = ",sender:getCurSelectedIndex())  
  184.         if dialog:isVisible() == true then  
  185.             dialog:setVisible(false)  
  186.         else  
  187.             ChatScene.showDialog()  
  188.         end  
  189.     end  
  190. end  
  191.   
  192. -- 滾動事件方法回調  
  193. local function scrollViewEvent(sender, eventType)  
  194.     -- 滾動到底部  
  195.     if eventType == ccui.ScrollviewEventType.scrollToBottom then  
  196.         print("SCROLL_TO_BOTTOM")  
  197.         -- 滾動到頂部  
  198.     elseif eventType == ccui.ScrollviewEventType.scrollToTop then  
  199.         print("SCROLL_TO_TOP")  
  200.     end  
  201.   
  202. end  
  203.   
  204. --[[  
  205. ====================  
  206. createChatLayer  
  207. 創建聊天層  
  208. ====================  
  209. ]]--  
  210. function ChatScene.createChatLayer()  
  211.   
  212.     ChatScene.uiLayer = cc.Layer:create()-- 創建ui層  
  213.     print("getReferenceCount1:"..ChatScene.uiLayer:getReferenceCount())  
  214.     winSize = cc.Director:getInstance():getWinSize()-- 獲得屏幕大小  
  215.   
  216.     ChatScene.setCurrentTag(TAG_WORLD)  
  217.     ChatScene.addOpenButton()  
  218.     ChatScene.findViews()  
  219.     ChatScene.setTouchEnabled()  
  220.     ChatScene.setTags()  
  221.     ChatScene.addTouchEventListener()  
  222.   
  223.   
  224.     -- 初始化三組數據  
  225.     local array = {}  
  226.     for i = 1, 20 do  
  227.         array[i] = string.format("請叫我巫大大%d", i - 1)  
  228.     end  
  229.   
  230.     local array1 = {}  
  231.     for i = 1, 20 do  
  232.         array1[i] = string.format("公會開放啦%d", i - 1 )  
  233.     end  
  234.   
  235.     local array2 = {}  
  236.     for i = 1, 20 do  
  237.         array2[i] = string.format("私聊列表項%d", i - 1 )  
  238.     end  
  239.   
  240.   
  241.     -- 創建模型  
  242.     local default_button = ccui.Button:create("cocosui/backtotoppressed.png""cocosui/backtotopnormal.png")  
  243.     default_button:setName("Title Button")  
  244.   
  245.     -- 創建默認item  
  246.     local default_itme = ccui.Layout:create()  
  247.     default_itme:setTouchEnabled(true)  
  248.     default_itme:setContentSize(default_button:getContentSize())  
  249.     default_button:setPosition(cc.p( default_itme:getContentSize().width / 2.0, default_itme:getContentSize().height / 2.0 ))  
  250.     default_itme:addChild(default_button)  
  251.   
  252.     -- 設置模型  
  253.     worldList:setItemModel(default_itme)  
  254.       
  255.       
  256.       
  257.     -- 這裏是5項  
  258.     --    for i = 1, math.floor( count / 4 ) do  
  259.     --        print("i:"..i)  
  260.     --        --  壓棧一個默認項(通過克隆創建的)進listView.  
  261.     --        worldList:pushBackDefaultItem()  
  262.     --    end  
  263.     --  
  264.     --    -- 插入默認項  
  265.     --    for i = 1, math.floor( count / 4 ) do  
  266.     --        -- 插入一個默認項(通過克隆創建的)進listView.  
  267.     --        worldList:insertDefaultItem(0)  
  268.     --    end  
  269.   
  270.     --使用cleanup清空容器(container)中的所有子節點(children)  
  271.     --    worldList:removeAllChildren()  
  272.   
  273.     --    local testSprite = cc.Sprite:create("cocosui/backtotoppressed.png")  
  274.     --    testSprite:setPosition(cc.p(200,200))  
  275.     --    worldList:addChild(testSprite)  
  276.   
  277.   
  278.     -- 獲得數組的大小  
  279.     local count = table.getn(array)  
  280.     print("count:"..count)  
  281.     -- 添加自定義item  
  282.     for i = 1, count do  
  283.         -- 創建一個Button  
  284.         local custom_button = ccui.Button:create("cocosui/button.png""cocosui/buttonHighlighted.png")  
  285.         -- 設置Button名字  
  286.         custom_button:setName("Title Button")  
  287.         --  設置按鈕使用九宮(scale9)渲染器進行渲染  
  288.         custom_button:setScale9Enabled(true)  
  289.         -- 設置內容尺寸  
  290.         custom_button:setContentSize(default_button:getContentSize())  
  291.   
  292.         -- 創建一個佈局  
  293.         local custom_item = ccui.Layout:create()  
  294.         -- 設置內容大小  
  295.         custom_item:setContentSize(custom_button:getContentSize())  
  296.         -- 設置位置  
  297.         custom_button:setPosition(cc.p(custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0))  
  298.         -- 往佈局中添加一個按鈕  
  299.         custom_item:addChild(custom_button)  
  300.         -- 往ListView中添加一個佈局  
  301.         worldList:addChild(custom_item)  
  302.   
  303.     end  
  304.   
  305.     --    local function customButtonListener(sender, touchType)  
  306.     --        if sender:getTag() == 1 then  
  307.     --            dialog:setVisible(true)  
  308.     --        end  
  309.     --    end  
  310.   
  311.   
  312.     for i = 1, 20 do  
  313.         local custom_button = ccui.Button:create("cocosui/button.png""cocosui/buttonHighlighted.png")  
  314.         custom_button:setName("wwj")  
  315.         custom_button:setScale9Enabled(true)  
  316.         custom_button:setContentSize(default_button:getContentSize())  
  317.   
  318.         local custom_item = ccui.Layout:create()  
  319.         custom_item:setContentSize(custom_button:getContentSize())  
  320.         custom_button:setPosition(cc.p(custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0) )  
  321.         custom_item:addChild(custom_button)  
  322.         partyList:addChild(custom_item)  
  323.     end  
  324.   
  325.     for i = 1, 20 do  
  326.         local custom_button = ccui.Button:create( "cocosui/button.png""cocosui/buttonHighlighted.png" )  
  327.         custom_button:setName("wwj")  
  328.         custom_button:setScale9Enabled(true)  
  329.         custom_button:setContentSize( default_button:getContentSize() )  
  330.   
  331.         local custom_item = ccui.Layout:create()  
  332.         custom_item:setContentSize( custom_button:getContentSize() )  
  333.         custom_button:setPosition( cc.p( custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0 ) )  
  334.         custom_item:addChild( custom_button )  
  335.         chatList:addChild( custom_item )  
  336.     end  
  337.   
  338.     for i = 1, 5 do  
  339.         local custom_text = ChatScene.RichText()  
  340.   
  341.         local custom_item = ccui.Layout:create()  
  342.         custom_item:setTouchEnabled(true)  
  343.         custom_item:setContentSize( custom_text:getContentSize() )  
  344.         custom_text:setPosition( cc.p( custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0) )  
  345.         custom_item:addChild( custom_text )  
  346.         chatList:addChild( custom_item )  
  347.   
  348.   
  349. --        local custom_button = ccui.Button:create("cocosui/button.png""cocosui/buttonHighlighted.png")  
  350. --        custom_button:setName("wwj")  
  351. --        custom_button:setScale9Enabled(true)  
  352. --        custom_button:setContentSize(default_button:getContentSize())  
  353.   
  354.         --        local custom_item2 = ccui.Layout:create()  
  355.         --        custom_item2:setContentSize(custom_button:getContentSize())  
  356.         --        custom_button:setPosition(cc.p(custom_item2:getContentSize().width / 0.6, custom_item2:getContentSize().height / 0.6) )  
  357.         --        custom_item2:addChild(custom_button)  
  358.         --        custom_button:setTag(i)  
  359.         --        custom_button:addTouchEventListener(customButtonListener)  
  360.         --        chatList:addChild(custom_item2)  
  361.   
  362.     end  
  363.   
  364.     -- 插入自定義item  
  365.     local items = worldList:getItems()--返回項的集合  
  366.     -- 獲得項的個數  
  367.     local items_count = table.getn(items)  
  368.     --    for i = 1, math.floor( count / 4 ) do  
  369.     --        local custom_button = ccui.Button:create("cocosui/button.png""cocosui/buttonHighlighted.png")  
  370.     --        custom_button:setName("Title Button")--改變widget的名字,使用名字可以更輕鬆地識別出該widget  
  371.     --        custom_button:setScale9Enabled(true)-- 設置按鈕使用九宮(scale9)渲染器進行渲染  
  372.     --        custom_button:setContentSize(default_button:getContentSize())  
  373.     --  
  374.     --        local custom_item = ccui.Layout:create()  
  375.     --        custom_item:setContentSize(custom_button:getContentSize())  
  376.     --        custom_button:setPosition(cc.p(custom_item:getContentSize().width / 2.0, custom_item:getContentSize().height / 2.0))  
  377.     --        custom_item:addChild(custom_button)  
  378.     --        custom_item:setTag(1)  
  379.     --        worldList:insertCustomItem(custom_item, items_count)  
  380.     --    end  
  381.   
  382.     -- 設置item data  
  383.     items_count = table.getn(worldList:getItems())  
  384.     for i = 1, items_count do  
  385.         -- 返回一個索引和參數相同的項.  
  386.         local item = worldList:getItem( i - 1 )  
  387.         local button = item:getChildByName("Title Button")  
  388.         local index = worldList:getIndex(item)  
  389.         button:setTitleText(array[index + 1])  
  390.     end  
  391.   
  392.     local partyListItems_count = table.getn(partyList:getItems())  
  393.     for i = 1, partyListItems_count do  
  394.         local item = partyList:getItem( i - 1 )  
  395.         local button = item:getChildByName("wwj")  
  396.         local index = partyList:getIndex(item)  
  397.         button:setTitleText(array1[index + 1])  
  398.   
  399.     end  
  400.   
  401.     local chatListItems_count = table.getn(chatList:getItems())  
  402.     for i = 1, 20 do  
  403.         local item = chatList:getItem( i - 1 )  
  404.         local button = item:getChildByName( "wwj" )  
  405.         local index = chatList:getIndex( item )  
  406.         button:setTitleText( array2[ index + 1 ] )  
  407.     end  
  408.   
  409.     -- 移除Tag=1的子節點  
  410.     --    worldList:removeChildByTag(1)  
  411.   
  412.     -- 移除項by index  
  413.     --    items_count = table.getn(worldList:getItems())  
  414.     -- worldList:removeItem(items_count - 1)  
  415.   
  416.     -- 設置ListView對齊方式爲橫向居中  
  417.     worldList:setGravity(ccui.ListViewGravity.centerVertical)  
  418.     --set items margin  
  419.     worldList:setItemsMargin(2.0)  
  420.     worldList:setBounceEnabled(true)  
  421.     -- 設置ListView對齊方式爲橫向居中  
  422.     partyList:setGravity(ccui.ListViewGravity.centerVertical)  
  423.     --set items margin  
  424.     partyList:setItemsMargin(2.0)  
  425.   
  426.     inputBox:addEventListener(textFieldEvent)  
  427.   
  428.     ChatScene.uiLayer:addChild(ChatScene.widget)  
  429.     ChatScene.widget:setVisible(false)  
  430.     --    ChatScene.uiLayer:registerScriptHandler(onExit)  
  431.   
  432.     return ChatScene.uiLayer  
  433. end  
  434.   
  435. local function ListViewItem()  
  436.     local layout = ccui.Layout:create()  
  437.   
  438.     layout:setSizePercent( cc.p( 200, 200 ) )  
  439.     layout:setBackGroundColorType( ccui.LayoutBackGroundColorType.solid )  
  440.     layout:setBackGroundColor(cc.c3b(255,0,0))  
  441.   
  442.     local image = ccui.ImageView:create("")  
  443.     layout:addChild(image)  
  444.     return layout  
  445. end  
  446.   
  447.   
  448. local function loadListViewItemFromJson()  
  449.     listview_item = ccs.GUIReader:getInstance():widgetFromJsonFile( "res/listview_item/listview_item.ExportJson" )  
  450.     head_icon = listview_item:getChildByTag( 6 )  
  451.     level = listview_item:getChildByTag( 7 )  
  452.     name = listview_item:getChildByTag( 8 )  
  453.     text = listview_item:getChildByTag( 9 )  
  454. end  
  455.   
  456.   
  457. --[[  
  458. ===================  
  459. 設置相關標記  
  460. ===================  
  461. ]]--  
  462. function ChatScene.setTags()  
  463.     worldButton:setTag(TAG_WORLD_BUTTON)  
  464.     partyButton:setTag(TAG_PARTY_BUTTON)  
  465.     chatButton:setTag(TAG_CHAT_BUTTON)  
  466.     sendButton:setTag(TAG_SEND_BUTTON)  
  467.     chat:setTag(TAG_CHAT_BUTTON2)  
  468.     lahei:setTag(TAG_LAHEI_BUTTON)  
  469.     closeButton:setTag(TAG_CLOSE_BUTTON)  
  470. end  
  471.   
  472.   
  473. --[[  
  474. ============================  
  475. findViews()  
  476. 找到UI控件  
  477. ============================  
  478. ]]--  
  479. function ChatScene.findViews()  
  480.     ChatScene.widget = ccs.GUIReader:getInstance():widgetFromJsonFile( "ChatUI_1/ChatUI_1.json" )  
  481.     ChatScene.widget:setPosition( cc.p( 40, 40 ) )  
  482.   
  483.     loadListViewItemFromJson()  
  484.     -- 獲得UI界面上的3個按鈕  
  485.     worldButton = ChatScene.widget:getChildByTag(6)  
  486.     partyButton = ChatScene.widget:getChildByTag(7)  
  487.     chatButton = ChatScene.widget:getChildByTag(8)  
  488.   
  489.     -- 獲得三個每個按鈕對應的三個面板  
  490.     wordPanel = ChatScene.widget:getChildByTag(5)  
  491.     partyPanel = ChatScene.widget:getChildByTag(9)  
  492.     chatPanel = ChatScene.widget:getChildByTag(10)  
  493.   
  494.     -- 獲得每個面板的ListView  
  495.     worldList = wordPanel:getChildByTag(13)  
  496.     partyList = partyPanel:getChildByTag(14)  
  497.     chatList = chatPanel:getChildByTag(15)  
  498.   
  499.     -- 獲得輸入框  
  500.     inputBox = ChatScene.widget:getChildByTag(11)  
  501.     sendButton = ChatScene.widget:getChildByTag(12)  
  502.   
  503.     dialog = ChatScene.widget:getChildByTag(20)  
  504.     chat = dialog:getChildByTag(21)  
  505.     lahei = dialog:getChildByTag(22)  
  506.     closeButton = dialog:getChildByTag(27)  
  507. end  
  508.   
  509. --[[  
  510. ==================  
  511. addTouchEventListener  
  512. 添加觸摸事件  
  513. ==================  
  514. ]]--  
  515. function ChatScene.addTouchEventListener()  
  516.     -- 設置按鈕監聽事件  
  517.     worldButton:addTouchEventListener(touchEvent)  
  518.     partyButton:addTouchEventListener(touchEvent)  
  519.     chatButton:addTouchEventListener(touchEvent)  
  520.     sendButton:addTouchEventListener(touchEvent)  
  521.     chat:addTouchEventListener(touchEvent)  
  522.     lahei:addTouchEventListener(touchEvent)  
  523.     closeButton:addTouchEventListener(touchEvent)  
  524.   
  525.     -- 設置ListView的監聽事件  
  526.     worldList:addScrollViewEventListener(scrollViewEvent)  
  527.     worldList:addEventListener(listViewEvent)  
  528.     partyList:addScrollViewEventListener(scrollViewEvent)  
  529.     partyList:addEventListener(listViewEvent)  
  530.     chatList:addScrollViewEventListener(scrollViewEvent)  
  531.     chatList:addEventListener(listViewEvent)  
  532.       
  533.     --- 鍵盤事件監聽回調方法  
  534.     local function onkeyPressed(keycode, event)  
  535.         print("keypress")  
  536.         if keycode == cc.KeyCode.KEY_BACKSPACE then  
  537.            local str = inputBox:getStringValue()  
  538.             str = string.sub( str, 0, string.len( str ) - 1 )  
  539.             inputBox:setText( str )          
  540.         end  
  541.     end  
  542.       
  543.     -- 鍵盤監聽事件  
  544.     local keyListener = cc.EventListenerKeyboard:create()  
  545.     keyListener:registerScriptHandler(onkeyPressed,cc.Handler.EVENT_KEYBOARD_PRESSED)  
  546.     local eventDispatcher = ChatScene.uiLayer:getEventDispatcher()  
  547.     eventDispatcher:addEventListenerWithSceneGraphPriority(keyListener, ChatScene.uiLayer)  
  548. end  
  549.   
  550.   
  551. --[[  
  552. ==================  
  553. RichText  
  554. 富文本  
  555. =================  
  556. ]]--  
  557. function ChatScene.RichText()  
  558.     local richText = ccui.RichText:create()  
  559.     richText:ignoreContentAdaptWithSize(false)  
  560.     richText:setContentSize(cc.size(100, 100))  
  561.   
  562.     local re1 = ccui.RichElementText:create( 1, cc.c3b(255, 255, 255), 255, "This color is white. ""Helvetica", 10 )  
  563.     local re2 = ccui.RichElementText:create( 2, cc.c3b(255, 255,   0), 255, "And this is yellow. ""Helvetica", 10 )  
  564.     local re3 = ccui.RichElementText:create( 3, cc.c3b(0,   0, 255), 255, "This one is blue. ""Helvetica", 10 )  
  565.     local re4 = ccui.RichElementText:create( 4, cc.c3b(0, 255,   0), 255, "And green. ""Helvetica", 10 )  
  566.     local re5 = ccui.RichElementText:create( 5, cc.c3b(255,  0,   0), 255, "Last one is red ""Helvetica", 10 )  
  567.   
  568.     local reimg = ccui.RichElementImage:create( 6, cc.c3b(255, 255, 255), 255, "cocosui/sliderballnormal.png" )  
  569.   
  570.     -- 添加ArmatureFileInfo, 由ArmatureDataManager管理  
  571.     ccs.ArmatureDataManager:getInstance():addArmatureFileInfo( "cocosui/100/100.ExportJson" )  
  572.     local arr = ccs.Armature:create( "100" )  
  573.     arr:getAnimation():play( "Animation1" )  
  574.   
  575.     local recustom = ccui.RichElementCustomNode:create( 1, cc.c3b(255, 255, 255), 255, arr )  
  576.     local re6 = ccui.RichElementText:create( 7, cc.c3b(255, 127,   0), 255, "Have fun!! ""Helvetica", 10 )  
  577.     richText:pushBackElement(re1)  
  578.     richText:insertElement(re2, 1)  
  579.     richText:pushBackElement(re3)  
  580.     richText:pushBackElement(re4)  
  581.     richText:pushBackElement(re5)  
  582.     richText:insertElement(reimg, 2)  
  583.     richText:pushBackElement(recustom)  
  584.     richText:pushBackElement(re6)  
  585.   
  586.     richText:setLocalZOrder(10)  
  587.   
  588.     return richText  
  589. end  
  590.   
  591. local function textFieldCompleteHandler()  
  592.   
  593. end  
  594.   
  595.   
  596. --[[  
  597. =====================  
  598. setTouchEnabled  
  599. 設置一些控件可觸摸  
  600. ====================  
  601. ]]--  
  602. function ChatScene.setTouchEnabled()  
  603.     -- 設置可觸摸  
  604.     worldButton:setTouchEnabled(true)  
  605.     partyButton:setTouchEnabled(true)  
  606.     chatButton:setTouchEnabled(true)  
  607.     sendButton:setTouchEnabled(true)  
  608.     chat:setTouchEnabled(true)  
  609.     lahei:setTouchEnabled(true)  
  610.     closeButton:setTouchEnabled(true)  
  611.     inputBox:setTouchEnabled(true)  
  612. end  
  613.   
  614. --[[  
  615. =================  
  616. setCurrentTag  
  617. 設置當前Tag  
  618. =================  
  619. ]]--  
  620. function ChatScene.setCurrentTag(tag)  
  621.     flag = tag;  
  622. end  
  623.   
  624. --[[  
  625. ================  
  626. 獲得當前Tag  
  627. ===============  
  628. ]]--  
  629. function ChatScene.getCurrentTag()  
  630.     return flag  
  631. end  
  632.   
  633. --[[  
  634. ===============  
  635. 顯示dialog  
  636. ===============  
  637. ]]--  
  638. function ChatScene.showDialog()  
  639.     local popup  = cc.Sequence:create(cc.ScaleTo:create( 0.0, 0.0 ),  
  640.         cc.ScaleTo:create( 0.06, 1.05 ),  
  641.         cc.ScaleTo:create( 0.08, 0.95 ),  
  642.         cc.ScaleTo:create( 0.08, 1.0 ),  
  643.         nil)  
  644.     dialog:setVisible(true)  
  645.     dialog:runAction( popup )  
  646. end  
  647.   
  648.   
  649. -- 返回場景  
  650. return ChatScene  

源碼也給你們準備好了,請再次叫我活雷鋒:http://download.csdn.net/detail/wwj_748/7725699
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章