我是Android和Java的新手。我想将一个变量(ac)从OnClickListener传递给另一个。我已经尝试过这种方式,但是我收到了这个错误:无法解析符号' ac'。你能帮帮我吗?
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);
}
});
答案 0 :(得分:3)
最简单的方法是声明全局变量。在onCreate范围之外而不是在其内部声明您的ac
。
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);
}
});
}