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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With