2011-01-26 50 views
0

我写这个代码,并收到错误:我收到错误“抱歉!应用程序Android_Name(process com.pckge)意外停止,请重试。”强制关闭?

"Sorry! The Application Android_Name(process com.pckge) has stopped unexpectedly. Please try again. Force Close"

有什么错误?

package com.pckge; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import java.util.Date; 

public class Now extends Activity implements View.OnClickListener { 
    Button btn; 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     btn.setOnClickListener(this); 
      updateTime(); 
     setContentView(btn); 
    } 

    @Override 
    public void onClick(View view) { 
     updateTime(); 
     // TODO Auto-generated method stub 

    } 

    private void updateTime() { 
     btn.setText(new Date().toString()); 
     // TODO Auto-generated method stub 

    } 
} 
+1

检查你的错误日志(在Eclipse中调试)你得到什么样的错误,并粘贴在这里 – Nanne 2011-01-26 13:11:58

回答

6

你行

btn.setOnClickListener(this); 

当 'BTN' 尚未初始化被调用。它是NULL,所以你不能调用它的成员。首先为其分配一个真正的按钮。

(注意,Button btn;只设置类型)

从下面的评论引述@jems因为我同意它: 添加行btn = new Button(this) super.onCreate之后应该可以解决问题,但也可能是最好用xml来定义你的布局

+2

这是正确的。在super.onCreate之后添加行btn = new Button(this)应该可以解决这个问题,但是最好用xml定义布局。 – Jems 2011-01-26 13:15:58

2

你需要初始化你的按钮。我假设你已经在XML中创建了按钮,并设置了android:name =“buttonID”。

Button btn; btn = findViewById(R.id.buttonID);

相关问题