I am making an activity that contains a ListView
and a Button
. Being new to Android I didn't notice that I was writing it in the fragment xml document.
I noticed that the java code generated when making an activity ( Activity.java
) pertains to the activity xml, not the fragment, as getViewById()
returns null when I try to get my ListView
or Button
.
My question is, should I move the layout from the fragment xml to the activity xml, or is there a way to call the fragment from the Activity.java
file?
I read up a bit on the use of fragments and saw that they are mainly used while having several tabs, or "mini-activities" (sorta) in the same window/activity. I will not be needing that functionality though. Should I still be making the layout in the fragment xml?
setcontentview(R.layout.activity_main)
to
setcontentview(R.layout.fragment_main)
and remove below code
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
from onCreate method thats it. now fragment remove from your activity.. also remove activity_main.xml no need to this xml...
/ You can add fragment in activity in java like this: Fragment manager is responsible to manage all fragments you will have. MyFragment is class that extends Fragment and myFragment is object of that class. ContainerId is optional /
FragmentManager manager=getFragmentManager();
MyFragment myFragment=new MyFragment();
FragmentTransaction transaction=manager.beginTransaction();
transaction.add(R.id.container,myFragment,"Stringtag");
transaction.commit();
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.