我正在开发一个Android计算器,我想添加用户点击其按钮时点击的数字 我添加了像这样的onclick
android:onClick="number(1)"
括号内的数字是我希望它附加在EditText中的数字 主要活动和功能的代码是
public void number(int medo){
EditText result = (EditText) findViewById(R.id.result);
result.setText(result.getText() + " " + medo);
}
但是当我在测试应用程序时单击任何按钮时它崩溃了所以任何人都可以告诉我如何解决这个问题但请快点
答案 0 :(得分:1)
您的方法需要有一个View参数,该参数将包含您单击的按钮。
因此,您的代码可能如下所示:
public void number(View v) {
EditText result = (EditText) findViewById(R.id.result);
// get the text from the button that was clicked and add it to the EditText
result.setText(result.getText() + " " + ((Button)v).getText().toString());
}
您无法在XML中设置参数。它应该是这样的:
android:onClick="number"
答案 1 :(得分:0)
另外我认为你必须调用toString。
result.getText().toString()
答案 2 :(得分:0)
onCLick应该是一个包含view
参数的方法。
此View
表示点击了视图(在本例中为Button
)。
你的方法应该是这样的:
public void number(View view)
要解决您的问题,我建议将android:tag
放入xml中。
对于您展示的Button
,您会这样做:
android:tag="1"
android:onClick="number"
并在number
函数中,您将执行类似的操作:
public void number(View view)
{
result.setText(result.getText() + " " + view.getTag().toString);
}
此外,我强烈建议将result
设为全局变量,并在onCreate()
中对其进行初始化,这样可以使代码更好,更高效