简体   繁体   English

onCreate 方法之外的 findViewById 方法?

[英]findViewById method outside the onCreate method?

lately, I was working on a very small training project.最近,我在做一个非常小的培训项目。 But there is one error in my code:但是我的代码中有一个错误:

public class MainActivity extends AppCompatActivity {
    TextView textView = (TextView) findViewById(R.id.textview);

    @override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView.setText("Welcome");
    }
}

but when I tried to cut the textview global variable and paste it inside the onCreate method, the error has gone.但是当我尝试剪切 textview 全局变量并将其粘贴到 onCreate 方法中时,错误消失了。 Why is this error occur although I already have inflated the textView in a global variable?!尽管我已经在全局变量中膨胀了 textView,但为什么会出现此错误?!

You need to call findViewById(...) after calling setContentView(...) .您需要在调用setContentView(...) findViewById(...) ...) 。

Fetching the view before inflating the layout isn't possible since there is no view.由于没有视图,因此无法在扩展布局之前获取视图。

findViewById() should only be used after setContentView() in onCreate. findViewById()只能在 onCreate 中的setContentView()之后使用。

That's where your entire layout get inflated.这就是你的整个布局被夸大的地方。 Only then you can access views using findViewById() .只有这样您才能使用findViewById()访问视图。

This is what you want:这就是你想要的:

public class MainActivity extends AppCompatActivity {
TextView textView;

@override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 

    textView = (TextView) findViewById(R.id.textview);

    textView.setText("Welcome");

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 findViewById在onCreate方法中给出NullPointer异常 - findViewById giving NullPointer exception in onCreate method 在onCreate之外的方法中添加视图 - Add a view in a method outside onCreate 在onCreate()方法之外,getActionBar()为null - getActionBar() is null outside the onCreate() method 如何在onCreate方法之外初始化CastContext - How to initialize CastContext outside of onCreate method 我可以在oncreate方法之外使用setContentView吗? - Can I use setContentView outside the oncreate method? 我的findViewByid在扩展片段上变成红色,即时通讯在onCreate方法上执行,不在onCreateView方法中 - My findViewByid turn red on extend fragment, im doing on onCreate method not in onCreateView method 找不到适合inflate(int)的方法,尝试在活动之外使用findViewbyID - No suitable method found for inflate(int), tryingto use findViewbyID outside of activity 可以在onCreate()方法之外设置Android TextView的文本吗? - Can the text of an Android TextView be set outside of the onCreate() method? 如何在 onCreate 方法之外初始化我的 RelativeLayoutButton? - How can I initialize my RelativeLayoutButton outside of onCreate method? 安卓 可以在onCreate()生命周期方法之外初始化对象吗? - Android. It's okay to init objects outside of onCreate() lifecycle method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM