我正在尝试为Android生成一个计数器应用程序。它有5个用于显示数字的TextView,一个计数器的图片和3个按钮。用于向数字添加1的按钮,用于从数字和重置按钮减少1的按钮。当我启动应用程序时,我立即收到一条消息,指出应用程序意外停止。我正在为java文件添加我的代码。请有人帮帮我吗?
Counter.java:
public class Counter extends Activity{
public int num=0;
public TextView txt1,txt2,txt3,txt4,txt5;
Button btnPlus, btnMinus, btnReset;
public void addOne(){
num++;
if(num >= 100000)
num = 0;
}
public void redOne(){
num--;
if(num <= -1)
num = 0;
}
public void reset(){
num = 0;
}
public void build(){
txt1.setText(num%10);
txt2.setText(num/10%10);
txt3.setText(num/100%10);
txt4.setText(num/1000%10);
txt5.setText(num/10000%10);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_counter);
txt1 = (TextView) findViewById(R.id.num1);
txt2 = (TextView) findViewById(R.id.num2);
txt3 = (TextView) findViewById(R.id.num3);
txt4 = (TextView) findViewById(R.id.num4);
txt5 = (TextView) findViewById(R.id.num5);
build();
btnPlus = (Button) findViewById(R.id.plus);
btnMinus = (Button) findViewById(R.id.minus);
btnReset = (Button) findViewById(R.id.reset);
btnPlus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addOne();
build();
}
});
btnMinus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
redOne();
build();
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
reset();
build();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_counter, menu);
return true;
}
}
答案 0 :(得分:1)
当您调用settext时,您需要传递一个String值。
请改用:
txt1.setText(num%10+"");
txt2.setText(num/10%10+"");
txt3.setText(num/100%10+"");
txt4.setText(num/1000%10+"");
txt5.setText(num/10000%10+"");
如上所述,您还应检查您是否没有除以零。