简体   繁体   中英

why does my app crashes when I try to find a view that is in different xml files

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView tv = (TextView)findViewById(R.id.text);
        tv.setText("hello world");

}

here the textview is present in a different xml file other than activity.main xml file.

To use views from XML you have to inflate them. setContentView(int id) is doing some background inflating for you on R.layout.activity_main but you can't get a handle to the TextView because it is not inflated. I can't imagine why you would want to do something with a view from a hierarchy that you are not displaying; in any case I doubt this is the way you want to go about it.

This simply won't work, as the current inflated view points to activity_main and the so the findViewById() method looks for TextView in the activity_main file.

For finding the TextView in other file, you will first have to inflate that view (in you case the another xml file).

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