如果我希望在单击按钮时发生某些事情,这两种方法有什么区别?第一个似乎简单得多。
布局中
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage" />
Activity 中
public void sendMessage(View v) {
// do whatever
}
或
private OnClickListener listener = new OnClickListener() {
public void onClick(View v) {
// do whatever
}
};
protected void onCreate(Bundle savedValues) {
// Capture our button from layout
Button button = (Button)findViewById(R.id.mybutton);
// Register the onClick listener with the implementation above
button.setOnClickListener(listener);
}
最佳答案
这个问题分为几个部分:性能、可维护性和个人偏好。
性能:使用 xml 方法会造成性能损失,因为框架必须使用反射来调用类的方法。 Gingerbread 及更高版本应该没问题(更好的 jit),但在此之前差异很明显。
我认为 xml 方法的可维护性较差,因为它将“代码事物”(方法名称)放在表示层中。弄清楚在何处设置了哪个处理程序需要勤奋的评论,而开发人员常常忘记添加这些评论。
与 2 类似,我相信在同一个地方进行字段分配 (findViewById) 和事件处理程序会更加清晰,因为我有一个“ View 初始化”区域。跨文件拆分它对我来说就像是一种折磨。使用 View /依赖项注入(inject)甚至更好。
附言您不必将监听器分配给字段,使用匿名类然后调用您的 Activity/fragment 的单个方法会更干净。
关于Android事件处理方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16764162/