使用 Android 和 XML 构建动态用户界面(6)
 
- UID
- 1066743
|

使用 Android 和 XML 构建动态用户界面(6)
现在看看 中 XmlGuiFormField 类的构造情况。
清单 3. XmlGuiFormField.java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
| package com.msi.ibm;
// class to handle each individual form
public class XmlGuiFormField {
String name;
String label;
String type;
boolean required;
String options;
Object obj; // holds the ui implementation
// or the EditText for example
// getters & setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public String getOptions() {
return options;
}
public void setOptions(String options) {
this.options = options;
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("Field Name: " + this.name + "\n");
sb.append("Field Label: " + this.label + "\n");
sb.append("Field Type: " + this.type + "\n");
sb.append("Required? : " + this.required + "\n");
sb.append("Options : " + this.options + "\n");
sb.append("Value : " + (String) this.getData() + "\n");
return sb.toString();
}
public String getFormattedResult()
{
return this.name + "= [" + (String) this.getData() + "]";
}
public Object getData()
{
if (type.equals("text") || type.equals("numeric"))
{
if (obj != null) {
XmlGuiEditBox b = (XmlGuiEditBox) obj;
return b.getValue();
}
}
if (type.equals("choice")) {
if (obj != null) {
XmlGuiPickOne po = (XmlGuiPickOne) obj;
return po.getValue();
}
}
// You could add logic for other UI elements here
return null;
}
}
|
现在更详细地查看 XmlGuiFormField 类。
- 有 6 个类级别成员:
- name 持有字段名称 — 这是数据值的字段名称,类似于 HTML 值的表单域名称或数据库列名。
- label 持有字段说明或显示给用户的值。
- type 表明要创建的用户界面字段的风格。
- text 表明这个字段是用一个 EditText 字段实现的,用于输入字母数字字符。这是最常用的值。
- numeric 也是一个 EditText,但它局限于数字值。
- choice 使这个字段成为一个下拉列表。
- required 是一个 Boolean 值,标志字段是否为必要字段。如果字段必要且没有填充,则当用户试图提交表单时,将向用户显示一条错误消息。
- options 是一个字符串值,用于为一个选择字段传送一个可用选项列表。这个字段对其他字段可用,可能用作一个 regex 表达式以进行验证,也可以被覆盖以指定一个默认值。
- obj 表示用户界面小部件。例如,这个变量持有一个 EditText,用于文本或数字字段。对于一个选择字段,obj 成员包含一个 spinner 小部件。这个方法将在本教程后面进一步解释。
- 不出所料,这些变量拥有几个 getters 和 setters。
- toString() 和 getFormattedResult() 方法都利用 getData() 方法,我们将稍后解释。
- 在 XmlGuiFormField 类中,您需要管理多种类型数据,因此代码需要明确表示数据如何存储和访问。getData() 方法检查这个类型字段并在 obj 字段上执行一个类型设置,以便与存储的对象正确交互。如果您想向这个框架添加新字段类型,可以扩展 getData() 方法来支持这种新字段类型(参见 末尾附近的注释)。
您现在有一种方法来存储和管理元数据。现在可以检查应用程序的运行情况,然后将各部分组合起来。 |
|
|
|
|
|