Android: 如何将参数从 OnClickListener 传递给另一个

Android: How to pass parameters from OnClickListener to another

我是 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);
    }
});

最简单的方法是声明全局变量。在 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);
    }
});

}