16

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
  • 1,134
  • 5
  • 31
  • 58
  • check this links this may helps you..[fragments vs activitys][1] [1]: http://stackoverflow.com/questions/10478233/android-need-some-clarifications-of-fragments-vs-activities-and-views – kalyan pvs Aug 07 '13 at 10:08
  • A Fragment is not completely stand-a-lone, it needs an activity as a host. While an activity can be instantiated on it's own. I see that as the major difference. – LuckyMe Aug 07 '13 at 10:09
  • [This is an another link, and it answers your question][1] [1]: http://stackoverflow.com/questions/10477997/difference-between-activity-and-fragmentactivity – Thomas Ny Aug 07 '13 at 10:13
  • thanks alot, can you help me about my described scenario? – Talib Aug 07 '13 at 10:14

1 Answers1

16

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); 
Azurespot
  • 3,066
  • 3
  • 45
  • 73
Sayed Jalil Hassan
  • 2,535
  • 7
  • 30
  • 42
  • actually 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? – Talib Aug 07 '13 at 11:35