Eval function in Dalvik
如果我知道一个变量的模式,例如R.id.edit_x其中x(1..N),则如何获得对给定EditText的引用,例如findViewByID(R.id.edit_1)。 Dalvik中是否有类似"评估"的功能? 谢谢。
尝试Java反射。 通过反射检索静态最终字段的讨论在这里-通过反射访问Java静态最终ivar值
也许,您可以检查roboguice。 这是一个用于Android的ioc框架,非常易于使用。 我从该项目的示例中复制了一些代码以显示如何使用它:
1 2 3 4 5 6 7 8 | public class AstroboyMasterConsole extends RoboActivity { @InjectView(R.id.self_destruct) Button selfDestructButton; @InjectView(R.id.say_text) EditText sayText; @InjectView(R.id.brush_teeth) Button brushTeethButton; @InjectView(tag="fightevil") Button fightEvilButton; // we can also use tags if we want } |
那么您就可以在代码中插入这些变量了!
hoha的答案很好。 您可以做的另一件事是创建一个查找表,该表将1..N映射到资源ID。 (假定您提前知道所有资源ID。)