Reputation: 10777
I am creating a fragment and adding it to a layout using java code. To do this, i created 2 classes and 2 layouts. One of the classes extends Fragment and other extends FragmentActivity. One of the xml files is the container and other is the fragment. Here is my code:
public class FragmentClass extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_layout, container,false);
return v;
}
}
And here is how i add the fragment to the layout:
public class Fragment_Activity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.container_layout);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.container_layout_eklenecek_yer);
if(fragment==null){
fragment=new FragmentClass();
fm.beginTransaction().add(R.id.container_layout_eklenecek_yer, fragment).commit();
}
}
}
This code works as i expect, but here is my question: I have a piece of code in Fragment_Activity class that says:
fragment=new FragmentClass();
and FragmentClass has no constructors. Is a default, empty constructor is called here, or onCreateView works as a constructor? I am confused here.
Thanks
Upvotes: 1
Views: 1801
Reputation: 5918
No.
You need a default constructor with fragments, a constructor that takes no arguments is a "default constructor" (this might be c++ terminology) because it allows you to construct an object, for certain.
Because Android might need RAM or something it can kill your fragments, it might also bring them back.
If you pass stuff to the constructor how will the Android OS know that stuff to pass it to you when it needs to re-create the fragment? It doesn't - this question has no answer.
Hence the default constructor.
When re-creating your fragment Android will attach an activity, and you can use onActivityAttached (or something to that tune, look up fragment life-cycles) to get the activity. If you know the activity implements/extends a whatever
you can cast that activity to a whatever
and store it, whatever you need to do.
The onCreateview method is what the name says: the thing that is called that returns a view. It is called when Android wants the view that represents your fragment, it is NOT a constructor, neither to be thought of, or in actual fact.
Upvotes: 7