使用json中的文本创建动态按钮

时间:2016-07-14 08:28:38

标签: json database xamarin.android

我通过json url连接数据库。我想添加与数据库中的对象一样多的按钮。我只需要动态地做。我无法找到解决方法。

1 个答案:

答案 0 :(得分:0)

如果您需要每个条目的按钮,您只需要获取所有条目,然后将JSON输出反序列化为您需要在项目中创建的对象类。例如,让我们承认您在数据库中的条目是单个varchar。您执行“SELECT * FROM table”之类的请求,在类似Entry.cs的类中获取json和反序列化,包含:

public string Text { get; set; }

然后,使用foreach语句和名为List的条目(例如条目),可以将所有结果作为集合获得。然后,使用此列表,您可以创建一个简单的foreach来创建按钮:

foreach (Entry entry in entries) {
    Button button = new Button(this)
    button.SetText(entry.Text);
    //Other button customizations, layoutparameters, etc
    view.AddView(button); /*Where view is the parent element where you want your buttons
    to be. Of course, you'll need a reference to it using FindViewById. It
    can be a linear layout for example, so all your buttons will align.
}

那应该是它。请注意,如果数据库中有大量条目,可能会有很多按钮,因此请考虑使用ScrollView。