setOnClickListener导致崩溃

时间:2014-03-17 11:41:47

标签: android

Button start_game;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);          
    start_game = (Button) findViewById(R.id.start_game);
    start_game.setOnClickListener(this);
    setContentView(R.layout.welcome);
 }

我不知道为什么,但是如果我删除行setOnClickListener我的应用程序就开始了(当然我的按钮没有做任何事情)。 Logcat给了我这个:

  

java.lang.RuntimeException: Unable to start activity ComponentInfo{de.test.testabc/de.test.testabc.Welcome}: java.lang.NullPointerException

1 个答案:

答案 0 :(得分:8)

您需要在获取UI元素之前使您的布局膨胀,否则findViewById会返回null,因此您会在{{1}处获得NullPointerException }}

start_game.setOnClickListener(this);