Where to place setContentView() in onCreate()?

与世无争的帅哥 提交于 2020-01-03 12:17:18

问题


I am a beginner in android and I want to know why is it that when I place my setContentView() after defining the TextView, my app crashes, i.e

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView tv=(TextView) findViewById(R.id.tv);
    Linkify.addLinks(tv, Linkify.WEB_URLS|Linkify.EMAIL_ADDRESSES|
            Linkify.PHONE_NUMBERS);
    setContentView(R.layout.activity_main);     //After TextView 
}

But when I put my setContentView() before defining the TextView then my app runs fine.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);   //Before TextView
    TextView tv=(TextView) findViewById(R.id.tv);
    Linkify.addLinks(tv, Linkify.WEB_URLS|Linkify.EMAIL_ADDRESSES|
            Linkify.PHONE_NUMBERS);
}

Why it is that & and how adding setContentView() before makes the difference ?


回答1:


setContentView() literally sets the views of your Activity. If you try to do something like TextView tv=(TextView) findViewById(R.id.tv);, then there is no view to find because you haven't set your views yet, and thus your app crashes. This is why you should put setContentView() before you try to access your views.




回答2:


You can execute any code you want before the setContentView() method as long as it doesn't refer to (parts of) the View, which isn't set yet.

Since your tv variable refers to the contents of the View, it can't be executed.




回答3:


When you are defining setContentView() after you declared TextView you are doing wrong because the object Id that you are initializing in TextView is contained inside that layout is unknown in the class until the seConteView() executed.



来源:https://stackoverflow.com/questions/30828611/where-to-place-setcontentview-in-oncreate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!