Why Android app crashes for initializing variable with findViewById(R.id.******) at the beginning of the class?

后端 未结 4 1418
萌比男神i
萌比男神i 2020-11-22 09:27

I was just testing input/output, there was no special purpose, this is the last code that had run successfully:

public class MainActivity extends AppCompatA         


        
4条回答
  •  心在旅途
    2020-11-22 09:59

    Instance member variables are initialized when the instance itself is initialized. It's too early for findViewById()

    Before onCreate() your activity does not yet have a Window that findViewById() needs internally. Before setContentView() (that you should be calling in onCreate()) there are no views to be found either.

    Therefore init your view references in onCreate() and after setContentView().

提交回复
热议问题