gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:11:50 25 4
gpt4 key购买 nike

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

}

关于java - Android:如何将参数从 OnClickListener 传递给另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28183078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com