Java Android:如何将参数从OnClickListener传递到另一个
我不熟悉android和Java。我想把一个变量(ac)从一个监听器传递到另一个监听器。我尝试过这种方法,但收到了以下错误:无法解析符号“ac”。你能帮我吗Java Android:如何将参数从OnClickListener传递到另一个,java,android,onclicklistener,Java,Android,Onclicklistener,我不熟悉android和Java。我想把一个变量(ac)从一个监听器传递到另一个监听器。我尝试过这种方法,但收到了以下错误:无法解析符号“ac”。你能帮我吗 Button Calculate = (Button) theLayout.findViewById(R.id.button); Button buttonb = (Button) theLayout.findViewById(R.id.buttonb); final TextView tvac = (TextView) theLayout
Button Calculate = (Button) theLayout.findViewById(R.id.button);
Button buttonb = (Button) theLayout.findViewById(R.id.buttonb);
final TextView tvac = (TextView) theLayout.findViewById(R.id.tvac);
final TextView tvh = (TextView) theLayout.findViewById(R.id.tvh);
final EditText eta = (EditText) theLayout.findViewById(R.id.eta);
final EditText etn = (EditText) theLayout.findViewById(R.id.etn);
final EditText etb = (EditText) theLayout.findViewById(R.id.etb);
Calculate.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Double a = new Double(eta.getText().toString());
Double n = new Double(etn.getText().toString());
Double ac = a*n;
tvac.setText(getResources().getString(R.string.tvresultados2) + " " + ac);
}
});
buttonb.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
double b = new Double(etb.getText().toString());
double h = ac/b; //error: cannot resolve symbol 'ac'
tvh.setVisibility(View.VISIBLE);
tvh.setText("h = " + h);
}
});
最简单的方法是声明全局变量。将您的
ac
声明在onCreate范围之外,而不是在onCreate范围之内
public Double ac; // global variable
@Override
public void onCreate(Bundle savedInstanceState){
Button Calculate = (Button) theLayout.findViewById(R.id.button);
Button buttonb = (Button) theLayout.findViewById(R.id.buttonb);
final TextView tvac = (TextView) theLayout.findViewById(R.id.tvac);
final TextView tvh = (TextView) theLayout.findViewById(R.id.tvh);
final EditText eta = (EditText) theLayout.findViewById(R.id.eta);
final EditText etn = (EditText) theLayout.findViewById(R.id.etn);
final EditText etb = (EditText) theLayout.findViewById(R.id.etb);
Calculate.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Double a = new Double(eta.getText().toString());
Double n = new Double(etn.getText().toString());
ac = a*n;
tvac.setText(getResources().getString(R.string.tvresultados2) + " " + ac);
}
});
buttonb.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
double b = new Double(etb.getText().toString());
double h = ac; //assign global variable into h
tvh.setVisibility(View.VISIBLE);
tvh.setText("h = " + h);
}
});
}
这似乎是一个范围问题。尝试将
ac
声明移到onClickListener
上方。我已经尝试了此选项,但要做到这一点,我需要将“ac”声明为最终值。然后将ac
移到一个字段(全局)变量。这是java的基础。请阅读一些toturial fx:谢谢大家,它现在正在工作