What's the core difference between fragment and activity? Which code can be written in fragment?
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 = new Intent(this,SomeActivity.class);
but inside a fragment you will have to do something like this:
Intent intent = new Intent(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.
@Override
public View onCreateView(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);
![Talib](https://i.stack.imgur.com/DK9Qp.jpg?s=256&g=1)
Talib
Updated on June 05, 2022Comments
-
Talib about 2 years
I have three tabs with three fragments each and one main activity, and i want to create the socket to send the message over wifi network, so where should i write the code for it? In that particular fragment class or main activity?
-
Talib almost 11 yearsactually i want to create socket in order to broadcast the message over LAN but now the button on which i will listen for the broadcast event is in one of the fragment,then can i write the broadcasting message code inside fragment?