1

我编写了以下代码并编译了它,但是当我运行该应用程序时,我收到错误android the application has stopped unexpectedly force close eclipse。我认为这是因为我没有初始化 Button 和 TextView 对象,但是当我初始化它们时,我丢失了令牌“;” 错误。这个错误的原因是什么。

package com.umer.first.project;

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 StartingPoint extends Activity {

int counter;
TextView display;
Button add, sub;
//add= new Button(this);
//sub=new Button(this);
//display=new TextView();
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_starting_point);

    add= (Button) findViewById(R.id.aButton);
    sub = (Button) findViewById(R.id.sButton);
    display= (Button) findViewById(R.id.tvButton);

    add.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            counter++;
            display.setText("The total is " + counter);
        }
    });

    sub.setOnClickListener(new View.OnClickListener() {

        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            counter--;
            display.setText("You counter is " + counter);

        }
    });
}

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

2 回答 2

6

Display是 a TextView,您不能将其转换为按钮。

display= (Button) findViewById(R.id.tvButton);
于 2012-07-22T11:12:13.943 回答
0

2.您已声明 display 为 TextView,但初始化为 Button这是一个 Casting Exception

display= (Button) findViewById(R.id.tvButton); ///// 错误的。

一定是。

display= (TextView) findViewById(R.id.tvButton);

1.在onCreate()方法之前将 View 声明为实例变量,然后在 onCreate() 中对其进行初始化。

于 2012-07-22T11:18:32.780 回答