我需要计算按钮上的点击次数并在TOAST上显示,当我尝试使用Android VM进行循环时
final Button button= (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
int contadorClicks =0;
public void onClick(View v) {
//definir accion
contadorClicks ++ ;
Toast.makeText(getApplicationContext(), contadorClicks, Toast.LENGTH_LONG).show();
}
});
答案 0 :(得分:0)
尝试: create int contadorClicks = 0;类中的字段,即活动或片段 然后在方法内使用
final Button button= (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//definir accion
contadorClicks ++ ;
Toast.makeText(getApplicationContext(), String.valueOf(contadorClicks), Toast.LENGTH_LONG).show();
}
});
或者您可以执行以下操作:
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//definir accion
Integer contadorClicks;
if (v.getTag() == null) {
contadorClicks = 0;
} else {
contadorClicks = (Integer) v.getTag();
}
contadorClicks++;
v.setTag(contadorClicks);
Toast.makeText(getApplicationContext(), String.valueOf(contadorClicks), Toast.LENGTH_LONG).show();
}
});
答案 1 :(得分:0)
您需要定义要在setOnClickListener方法之外增加的变量。另外,正如我之前所建议的那样,使用String.valueOf(contadorClicks)获取int的String represantation。
int contadorClicks = 0;
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//definir accion
contadorClicks++;
Toast.makeText(getApplicationContext(), String.valueOf(contadorClicks), Toast.LENGTH_LONG).show();
}
});
答案 2 :(得分:0)
发生的事情是你的变量contadorClicks总是为0,因为每次点击按钮都会创建它。您需要做的是将该变量放在onClickListener之外。希望这有帮助
int contadorClicks = 0;
final Button button= (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//definir accion
contadorClicks ++ ;
Toast.makeText(getApplicationContext(), contadorClicks, Toast.LENGTH_LONG).show();
}
});