我正在 Eclipse 中编写 Android 计算器。我希望能够为多个变量设置 OnClickListener,而不必为每个变量编写一个监听器。看起来有点矫枉过正。有没有办法使用数组来做到这一点?非常感谢您的帮助。
封装 rechee.cool;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class HelloAndroidActivity extends Activity {
/** Called when the activity is first created. */
int counter=0;
//Just have two buttons so far, I'm going to have like 10 more
Button one;
Button two;
EditText display;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Associate the button variable with the xml reference
one= (Button) findViewById(R.id.bOne);
display= (EditText) findViewById(R.id.editText1);
//When button is clicked, display the text. How do I do this for the rest of my variables?
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//String string= Integer.toString(counter);
display.setText("1");
}
});
}
}
最佳答案
我执行此操作的方法是将 XML 中的相同 onClick
属性添加到每个按钮,如下所示:
<Button android:onClick="onButtonClick"
... />
然后将该属性中使用的方法添加到您的 Activity 中,通过 id 区分按钮:
public void onButtonClick(View v) {
switch(v.getId()) {
case R.id.button1:
// do something when button 1 is pressed
break;
case R.id.button2:
// do something when button 2 is pressed
break;
// and so on ....
}
}
或者,您可以使用 findViewById()
获取每个按钮,并将相同的监听器分配给所有按钮。然后通过onClick()
内部的id进行区分,如上所示。不过,这增加了一些无用的代码行,所以我认为这里的示例稍微更干净一些。
关于java - 需要一种更简单的方法来为 Android 计算器程序中的多个变量设置 onClickListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9253993/