📜 ⬆️ ⬇️

Little bit about fragment

Good afternoon Habr, in this article I want to talk about such an interesting element as Fragment, this article is not a scientific breakthrough, but just a small tutorial on the use of this element. Anyone who is interested to know something new, please under the cat.

Fragment is a modular part of an activity that has its own life cycle and its own handlers for various events. Android added fragments with API 11, so that developers can develop more flexible user interfaces on large screens, such as tablet screens. After some time, the library was written, which adds support for fragments in older versions.

The advantages compared with the use of activity are immediately visible:


Main classes


There are three main classes:
android.app.Fragment - from him, strictly speaking. and our fragments will be inherited
android.app.FragmentManager - using an instance of this class, all interaction between fragments occurs
android.app.FragmentTransaction - well, this class, as the name implies, is needed to complete transactions.
Currently, there are variations of the class Fragment, for solving certain problems - ListFragment, PreferenceFragment, etc.
')

The basics of working with fragments


To create a fragment, all you need is to inherit your class from a Fragment. To bind a fragment to a specific markup, you need to define the onCreateView () method in it. This method returns the View to which your fragment belongs.

public class ExampleFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.you_layout_for_fragment, container, false); return view; } } 


To get this View from anywhere in the fragment, just call getView ().

We created the fragment, but I would like to place it on the screen. To do this, we need to get an instance of FragmentManager and complete the transaction we need.
First you need to know what we can do with the fragment:
add () - add fragment
remove () - remove a fragment
replace () - fragment replacement
hide () - makes the fragment invisible
show () - displays a fragment

You can also use addToBackStack (String) to add our transactions to the stack, as it happens by default with activities, and to return to the previous state of the stack, call the popBackStack () method.

Add a fragment to the screen:

 ExampleFragment youFragment = new ExampleFragment(); FragmentManager fragmentManager = getFragmentManager() fragmentManager.beginTransaction() //   FragmentTransaction .add(R.id.container_for_fragments, youFragment) .addToBackStack("myStack") .commit(); //  commit    FragmentTransaction 


How to connect activity and fragment?


To call activation methods, it is enough to get its instance through the getActivity () method .

 if (getActivity() != null) MainActivity act = (MainActivity ) getActivity(); 


For the same to get access to the fragment, we have a link to the object of the fragment, which we created during the transaction

If we need to handle fragment events from the activation, then the best solution is to activate the interface to implement it and in the fragment try to bring the parent activation to the object of this interface.

Sometimes we need to transfer some value or a whole object to a fragment, for example, we have a shopping list by clicking on an item which opens a detailed description of this purchase. Immediately I want to take and pass this parameter through the fragment constructor, but google categorically does not advise overriding the fragment constructors. Therefore, there are two ways out of this situation.
  • serialize an object
  • pass an object in the Parcel container by overriding the Parcable methods
  • in some places I saw that to create a fragment through an overridden constructor, they create a static factory method


I will show how this is done for the second option, since for android it is more correct to use Parcel to transfer parameters between activities and fragments.

 public class MyObject implements Parcelable { public String paramOne; public int paramToo; public MyObject(String paramOne, int paramToo) { this.paramOne = paramOne; this.paramToo = paramToo; } private MyObject(Parcel parcel) { //    Parcel paramOne = parcel.readString(); paramToo = parcel.readInt(); } public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int flags) { //   Parcel parcel.writeString(paramOne); parcel.writeInt(paramToo); } public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject>() { //        public MyObject createFromParcel(Parcel in) { return new MyObject(in); } public MyObject[] newArray(int size) { return new MyObject[size]; } }; } 


Here we have implemented the Parcelable interface in the class that we want to pass between fragments.
To transfer it to the fragment, do the following:

 MyObject obj = new MyObject("", 1 ); Bundle bundle = new Bundle(); bundle.putParcelable("key", obj); youFragment.setArguments(bundle); 


Then you just need to get the object passed by us in the onCreateView () method of the new fragment:
  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.you_layout_for_fragment, container, false); if(getArguments() != null) MyObject obj = getArguments().getParcelable("key"); return view; } 


UPD. fixed getting obj from getArguments (), thanks to firexel

Fragment animation


We learned how to create fragments, perform actions on them, interact with activations and activations, but in order to make them look presentable, fragments can be animated a little by adding animations to them.

To create your own animation of adding and deleting a fragment? you need to create two files in the res / animator directory, one of them will serve to animate the add, the second to remove

I will give an example of one of them:

 <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:ordering="together"> <objectAnimator xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_decelerate_interpolator" android:propertyName="x" //    android:valueType="floatType" android:valueTo="0" //    android:valueFrom="1280" //    android:duration="2000"/> //  </set> 


The root element is the objectAnimator, its attributes and set animation parameters.
Now we need to call the setCustomAnimations () method with our animations and our fragments will come to life in the next transaction.

 ExampleFragment youFragment = new ExampleFragment(); FragmentManager fragmentManager = getFragmentManager() fragmentManager.beginTransaction() .setCustomAnimations(R.animator.show_fr, R.animator.remove_fr); .add(R.id.container_for_fragments, youFragment) .addToBackStack("myStack") .commit(); 


Much more can be said about the fragments, although most of everything has already been written, but I wanted to combine all the basic knowledge about the fragments so that a person who knows nothing about this element, after reading, becomes free to use them.

Source: https://habr.com/ru/post/207036/


All Articles