1

这段代码有什么错误?当我运行程序时,它说“应用程序 buttonProj(进程 com.example.buttonproj)已意外停止。请重试”我只是尝试创建一个添加和减去按钮,用户可以单击它来增加或减少数字 i .

  package com.example.buttonproj;

 import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

 import android.view.View;
 import android.widget.Button;
   import android.widget.TextView;


 public class MainActivity extends Activity {

int counter;
Button add, sub;
TextView display;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    counter = 0;

   add = (Button) findViewById(R.id.bAdd);
   sub = (Button) findViewById(R.id.bSub);
   display = (TextView) findViewById(R.id.textView1);

   add.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub
        counter +=1;
        display.setText(counter);
    }
});
   sub.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
        // TODO Auto-generated method stub
        counter--;
        display.setText(counter);


    }
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}


}
4

1 回答 1

5

采用

display.setText(""+counter);
 //OR
display.setText(String.valueOf(counter));

代替

display.setText(counter);
于 2012-07-17T14:00:04.953 回答