Reputation: 435
I'm following along with the tutorial here
https://developer.android.com/training/basics/firstapp/building-ui.html
and I'm confused as to why they say to edit fragment_main.xml instead of activity_main.xml. In the MainActivy.java file, the onCreate() method has a line that says
setContentView(R.layout.activity_main);
Why does it complain when I try to change it to
setContentView(R.layout.fragment_main);
Any pointers would be appreciated.
Upvotes: 0
Views: 5532
Reputation: 477
Both are optional. But, It's always better using one layout to avoid confusion into your code. Which in this case I will suggest using activity_main.xml
and delete the fragment_activity.xml
following the below procedure:
1.Creat project normally.
2.Copy fragment_main.xml
to activity_main.xml
(content). Then delete fragment_main.xml
3.In MainActivity.java
delete the following content :
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
and
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
Hope this help
Upvotes: 0
Reputation: 4372
its just name fragment_main
or activity_main
if you wish you can give your GF :D name also,
i.e when you add a layout file to res/layout path an entry will be maid in R.java
say you create main.xml
in res/layout
, and when you clean your project an entry R.layout.main
will be added to R.java
its just the name whatever you give to file.
may be you getting error because that file not there or might be that file don't hold layout in it.
Upvotes: 0
Reputation: 3257
The activity is a container of fragments, a fragment is like an UI layer which can be added, modified or deleted in execution time. also in the activity layout you can have added "static" fragments.
There can be a lot of causes for your error if you swap the layouts, maybe your activity code tries to reference some views that are not in the fragment layout or viceversa, maybe the activity layout has references to fragments, etc... You can name your layouts as you want, but you need to set the layout that matches with your code in your activities/fragments
Upvotes: 2
Reputation: 2088
you have to use
setContentView(R.layout.activity_main);
in your program where as setContentView(R.layout.fragment_main); is used when you use Different Fragments in One Activity
and you getting error because there is no xml file present named fragment_main.xml in res folder.
Upvotes: 0