Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the core difference between fragment and activity? Which code can be written in fragment?

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?

like image 413
Talib Avatar asked Aug 07 '13 10:08

Talib


1 Answers

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); 
like image 99
Sayed Jalil Hassan Avatar answered Sep 19 '22 17:09

Sayed Jalil Hassan