[英]android app force closes
我有这个android代码。我在xml文件中定义了按钮的布局。我想在这里通过id获得按钮的文本来设置按钮的文本。但是应用程序强制关闭了。
package com.action ;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class ActionActivity extends Activity {
@Override
public void onCreate(Bundle i){
super.onCreate(i);
Button button=(Button) findViewById(R.id.but);
button.setText("Hey!!");
setContentView(R.layout.main);
}
}
谢谢...
您必须使用setContentView(R.layout.main);
在使用findViewById()
之前。
如果不这样做,则findViewById()
将返回null
(因为当前布局中没有该ID的视图),并且在尝试在TextView
上设置文本时会收到NullPointerException
。
正确的onCreate()
版本应如下所示:
public void onCreate(Bundle i) {
super.onCreate(i);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.but);
button.setText("Hey!!");
}
在创建Button实例之前,将setContentView(R.layout.main)放入。 像这样:
setContentView(R.layout.main);
Button button=(Button) findViewById(R.id.but);
button.setText("Hey!!");
您必须在设置findViewById(R.id.but)之前放置setContentView(R.Layout.main)。因为它会生成nullpointer Exception。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.