[KEY : FRAGMENT, ADDING FRAGMENT, ANDROID FRAGMENT, CREATING FRAGMENT]
FRAGMENT, ANDROID
Android activity is simple and best way to provide interface to user. Fragment are very similar to activity. But it will be much better if we call it small piece of activity. So an activity can have multiple fragments
Creating fragment in android
- Create simple class like "MyFirstFragment.java".
- Extend Fragment class into "MyFirstFragment.java".
- Fragement is almost ready. Now add required methods into it, Specifically you require two methods onCreateView() and onAttach() as mentioned below :
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return super.onCreateView(inflater, container, savedInstanceState); }
@Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); }
- Inflate your own xml file and return it as view. So finally onCreateView() will look like as below:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View localView = inflater.inflate(R.layout.your_xml.xml, container, false); return localView; //super.onCreateView(inflater, container, savedInstanceState); } - Create global object of your parent activity
YourActivity yourActivityObject;
- Initialize yourActivityObject in onAttach method so it will look as below:
@Override public void onAttach(Activity activity) { yourActivityObject = (YourActivity)activity; super.onAttach(activity); }
Start / Call new fragment from fragment
Fragment yourSecondFragment = new YourSecondFragment();
FragmentManager fm = yourActivityObject.getSupportFragmentManager();
//yourSecondFragment.setArguments(Bundle) // to pass argument to next fragment.
fm.beginTransaction().replace(R.id.parent_activity_frame_layout,
yourSecondFragment).addToBackStack("myfragmentstring").commit();
// addToBackStack method before commit is used to implement back button functionality later.
Adding back button functionality to fragment
In parent activity add onBackPressed() method and paste the following code
int f = getSupportFragmentManager().getBackStackEntryCount();
Log.v(tag, "onBackPressed ["+f+"]");
if (f <= 1)
this.finish();
else {
getSupportFragmentManager().popBackStackImmediate();
}
No comments:
Post a Comment