2012-05-27 48 views
1

在我的Android应用程序,我有一个像如何以良好的方式从UI元素创建对象?

MyButton a; 
MyEditText b; 
MySpinner c; 
MyTextView d; 

某些领域每一种是像public class MyButton extends Button implements InfoExtract

public interface InfoExtract{ 
    String getTheText(); 
} 

在这些领域(用户可以更改其中的一些),有一个用户配置要像这样创建的:

public class ProfileUpdate { 
    // The fields have to be string no matter what 
    String firstName; 
    String lastName; 
    String dateOfBirth; 
    String relationshipStatus 
} 

的执行流程是这样的:

List<InfoExtract> uiElements = new ArrayList<InfoExtract>(); 
uiElements.add(a); 
uiElements.add(b); 
uiElements.add(c); 
uiElements.add(d); 
someButton.setOnClickListener(new SaveProfileListener(uiElements); 

SaveProfileListener或多或少地做到这一点:

ProfileUpdate pup = new ProfileUpdate(); 
int i = 0; 
pup.firstName = uiElements.get(i++).getTheText() 
pup.lastName = uiElements.get(i++).getTheText(); 
pup.dateOfBirth = uiElements.get(i++).getTheText(); 
pup.relationshipStatus = uiElements.get(i++).getTheText(); 

坏事#1:如果我想添加其他领域的显着大量的工作。

坏事#2:列表中元素的顺序很重要。

不好的事情#3:例如,我不能轻易操作dateOfBirth的日期格式。

什么我可以做,但什么是同样糟糕:

// Pass the listener what fields it should use. 
someButton.setOnClickListener(new SaveProfileListener(a, b, c, d); 

如何使这个漂亮和干净的?

回答

0

我最终为每个字段使用了一个Map和一个新的Enum类型。

相关问题