What's The Core Difference Between Fragment And Activity? Which Code Can Be Written In Fragment?
Solution 1:
Of course you can write any code inside the fragment but you need to take care of a few things. While accessing anything that requires a context or something that is specific to an activity you will need to get a reference to the super activity of the fragment, e.g. while creating an intent inside an activity you do something like this :
Intent intent = newIntent(this,SomeActivity.class);
but inside a fragment you will have to do something like this:
Intentintent=newIntent(super.getActivity(),SomeActivity.class);
Similarly if you are accessing some thing from the layout file of the fragment. You need to perform the following steps:
1)get a global reference to the parent layout of your fragment inside your fragment. e.g
private LinearLayout result_view;
2) Implement the OnCreateView method instead of onCreate method.
@OverridepublicViewonCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return result_view;
}
3) Inflate the fragment layout like this inside the onCreateView method of the fragment:
result_view = (LinearLayout) inflater.inflate(
R.layout.image_detail_pager, container, false);
4) you can now access layout views like this :
layout_a = (LinearLayout) result_view
.findViewById(R.id.some_layout_id);
Post a Comment for "What's The Core Difference Between Fragment And Activity? Which Code Can Be Written In Fragment?"