Tuesday, June 3, 2014

Android Fragments

Android fragments were introduced for making the life easier for doing the multi panel interfaces and dynamic UIs. Fragments almost act like nested activities. 
A fragment can be created using Fragment class. 

Fragments have its own life cycle events, receives its own input events. or can be removed while the activity is still running. If the app supports API level less than 11, then app may can use the support library provided for fragments. If the app is built for supporting API level 11 or high, then it can just use the Fragment class and related APIs. 

To create the fragment, just needs to extend the Fragment class and override its life cycle events to do the app activities. 

import com.android.os.Bundle;
import com.android.support.v4.app.Fragment;
import android.view.LayoutInflator;
import android.view.ViewGroup;

public class ArticleFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflator inflator, ViewGroup container, Bundle savedInstanceStage)
{
return Inflator.inflate(R.layout.article_view,container,false);
}
}

Fragments also can override other life cycle methods such as onPause() 

On API levels 11 or higher, we can add Fragments to the Activity itself, but on prior versions, we would need to have FragmentActivity.

Fragments are declared in layout XML file much similar to the Views. An example is like below 

android:id="@+id/headlines_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent"
/>

the one noticeable limitation is that if the fragment is defined as part of the layout xml file, the fragment cannot be removed at runtime. If there is a plan to remove the fragment at runtime, then we need to add as part of the activity load. 


No comments:

Post a Comment