[英]Scope of final variable not visible to OnClickListener
I am a beginner, I'm trying to build a calculator. 我是一个初学者,我正在尝试构建一个计算器。 I have a problem.
我有个问题。
I write the answer like this: 我这样写答案:
ans += Double.parseDouble(etResult.getText().toString());
outTest.setText("The answer is " + ans);
This is in an OnClickListenter. 这在OnClickListenter中。 The problem is that I have to communicate with the double ans, which I defined in the beginning of my project, if I want to communicate with the double I need him to be final, but if he is final I cant change him in the OnClickListener.
问题是我必须与在项目开始时定义的double ans进行通信,如果我想与double进行通信,我需要他是final,但是如果他是final,则无法在OnClickListener中进行更改。
Can anyone help me and tell me how can I do this? 谁能帮助我,告诉我该怎么做? thanks.
谢谢。
使用通常的技巧:代替double ans = 0
声明final double[] ans = {0}
,然后可以在处理程序代码中使用ans[0] += ...
You can writ your code as follows 您可以如下编写代码
public class TestActivity extends Activity {
/** Called when the activity is first created. */
Double dbl;
Button btn;
EditText et;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
et = (EditText) findViewById(R.id.editText1);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
dbl = Double.parseDouble(et.getText().toString());
Log.e("double", "" + dbl);
}
});
}
} }
Try it 试试吧
public class TestActivity extends Activity {
/** Called when the activity is first created. */
Double dbl;
Button btn;
EditText et1, et2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
dbl = Double.parseDouble(et1.getText().toString());
et2.setText(dbl.toString());
}
});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.