将setContentView()放在onCreate()中的哪里? [英] Where to place setContentView() in onCreate()?

查看:353
本文介绍了将setContentView()放在onCreate()中的哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android的初学者,我想知道为什么为什么在定义 TextView 后放置 setContentView()时,我的 app崩溃了,即

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 
}

但是当我在定义TextView之前放置 setContentView()时,我的应用程序运行良好.

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);
}

为什么是&以及如何在添加setContentView()之前 差异?

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

推荐答案

setContentView()从字面上设置您的活动"视图.如果您尝试执行类似TextView tv=(TextView) findViewById(R.id.tv);的操作,则找不到视图,因为尚未设置视图,因此您的应用程序崩溃了.这就是为什么在尝试访问视图之前应先放置setContentView()的原因.

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.

这篇关于将setContentView()放在onCreate()中的哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆