STEP 1 创建一个Scroll View组件:
创建一个Scroll View组件,为content添加一个Grid Layout Group和一个Content Size Fitter组件,Grid Layout Group在添加新项目的时候自动生成布局,Content Size Fitter再添加新项目的时候自动扩展宽度或者高度。详细步骤参见:http://blog.csdn.net/Du_youlu/article/details/75330942
STEP 2 创建Item模板:
首先使用UGUI创建一个列表Item样式,放置于content下,
STEP 3 绑定脚本动态生成Item:
为camera(或其他)绑定如下脚本:
public GameObject originObject;//list item
public Transform parentTransForm;//whole list
void Start () {
StartCoroutine(LoadMusicInfo());
}
IEnumerator LoadMusicInfo()
{
string url = "http://songshizhao.com/********.asmx/AllMusicInfo";
WWW www = new WWW(url);//这部分看www的API,你懂的
yield return www;
XmlDocument xml = new XmlDocument();
try
{
xml.LoadXml(www.text);
XmlElement tables = xml.DocumentElement;
foreach (XmlElement item in tables)
{
var str = item.InnerText.Split(',');
MuiscInfo MI = new MuiscInfo()
{
ID = str[0],
BundleName = str[1],
AssetName = str[2],
BundleVarient = str[3],
Singer = str[4],
Maker = str[5],
};
MuiscInfos.Add(MI);
Debug.Log(str[1]);
}
}
catch (System.Exception ex)
{
//...
}
foreach (var item in MuiscInfos)
{
//GameObject.Instantiate(originObject, parentTransForm);
GameObject clone =(GameObject)Instantiate(originObject, parentTransForm);
clone.transform.localScale = new Vector3(1, 1, 1);
Transform[] allChildren = clone.GetComponentsInChildren<Transform>();
foreach (var child in allChildren)
{
switch (child.name)
{
case "startbutton":
child.GetComponent<Button>().GetComponent<BeginPage_StartButton>().MusicInfo = item;
//child.GetComponent<Button>().onClick.AddListener(delegate () {this.OnBtnClick(child.tag);});
Debug.Log(item.SongName);
break;
case "songname":
child.GetComponent<Text>().text = item.SongName;
break;
case "singer":
child.GetComponent<Text>().text = item.Singer;
break;
default:
break;
}
}
//Debug.Log("Finished");
}
//originObject.SetActive(false);
}
在编辑器中分别将content和listItem分别拖动到originObject和parentTransForm对应,异步加载网络数据动态克隆listitem。
STEP 4 点击Item-Button执行不同操作:
如果想要为button添加执行事件,在编辑器中为模板ListItem的startButton添加一条脚本。button绑定自身方法,建立一条属性MusicInfo并在克隆时分别赋值
public MuiscInfo MusicInfo { get; set; }
void Start () {
}
void Update () {
}
public void OnClick()
{
GameObject buttonsound = GameObject.Find("Audio Source");
buttonsound.GetComponent<AudioSource>().Play();
//...
Debug.Log(MusicInfo.AssetName);
}
Listitem绑定自身的onclick处理函数,MusicInfo属性在生成的时候动态赋值,这样button在点击时候获得其背后代表不同的数据,达到类似数据绑定的效果。
STEP 5 隐藏模板:
将ListItem拖动到资源作为prefab,使用prefab进行克隆,切断关联后删除原有Listitem,这样被克隆item就不会显示了。
(the end)