cocos2d-x lua 使用ListView

cocos2d-x lua 使用ListView

version: cocos2d-x 3.6


本文主要讲述:使用Cocos Studio创建ListView,和列表项的模板,代码中通过模板创建列表的每一项,并替换其中的图片文字等。


1. 加载Cocos Studio编辑好的资源

-- //cocos studio 中资源的名字
M.srcLayer = {
    ["listView"] = "list_view",
    ["btnFriends"] = "button_friends",
    ["btnAround"] = "button_around",
}
M.srcListItem = {
    ["bg"] = "image_bg",
    ["img"] = "image_head",
    ["name"] = "lable_name",
    ["meter"] = "lable_meter",
}

function M:loadLayout()
	if self.m_resNode then
		self.m_resNode:removeSelf()
		self.m_resNode = nil
	end
	self.m_resNode = cc.CSLoader:createNode("ui/layer_test_listview.csb")  -- //load your layout csb
	assert(self.m_resNode, string.format("ViewBase:createResourceNode() - load resouce node from file \"%s\" failed", resourceFilename))   
	self:addChild(self.m_resNode)

	local listView = self.m_resNode:getChildByName(M.srcLayer.listView)
end

2. 更新ListView的每一项

function M:refreshListView()
    local listView = self.m_resNode:getChildByName(M.srcLayer.listView)
    assert(listView,"")
    listView:removeAllChildren()
    
    
    local friendList = {
		{["id"]="1234567890", ["name"]="testName", ["picture"]="test.png"},
		{["id"]="1234567890", ["name"]="testName", ["picture"]="test.png"},
		{["id"]="1234567890", ["name"]="testName", ["picture"]="test.png"},
		{["id"]="1234567890", ["name"]="testName", ["picture"]="test.png"},
	}
    for idx, oneFriend in pairs(friendList) do
		
		-- //加载模板项
        local oneItem = cc.CSLoader:createNode("ui/layer_test_listview_item.csb")
		
        local imgBg = oneItem:getChildByName(M.srcListItem.bg)
        local imgHead = oneItem:getChildByName(M.srcListItem.img)
        local lableName = oneItem:getChildByName(M.srcListItem.name)
        local lableMeter = oneItem:getChildByName(M.srcListItem.meter)
        -- //reset
		--imgHead:initWithFileName(oneFriend.picture) --//imgHead是精灵类Sprite
        lableName:setString(friendInfo.name)
        --lableMeter:setString(tostring(oneFriend.meter))
		
        --//create layout
        local listItemLayout = ccui.Layout:create()
        listItemLayout:setContentSize(imgBg:getContentSize())
        listItemLayout:addChild(oneItem)
        oneItem:setPosition(cc.p(listItemLayout:getContentSize().width / 2.0, listItemLayout:getContentSize().height / 2.0))
        listItemLayout:setTag(idx)
        listView:insertCustomItem(listItemLayout, 0)
    end
end

3. 其他

  • 如果想在代码里面创建listview和它的每一个列表项,可直接参照lua test里面的代码
  • 注意编辑cocos studio资源的时候不要去拖动每一个空间的4个顶点去缩放它
  • 使用page view 和 table view 类似
posted @ 2015-06-06 17:10  、拂晓  阅读(6532)  评论(0编辑  收藏  举报