简体   繁体   中英

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. Why is this error occur although I already have inflated the textView in a global variable?!

You need to call findViewById(...) after calling setContentView(...) .

Fetching the view before inflating the layout isn't possible since there is no view.

findViewById() should only be used after setContentView() in onCreate.

That's where your entire layout get inflated. Only then you can access views using 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");

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM