Example explanation of android app using fragment in viewpager
It is said that Android most recommends the use of fragment in viewpager, that is, the pages in viewpager are not loaded directly from the layout file with layoutinflator as before, but fragments. Notice the fragment here
It is the fragment in the android.support.v4.view package, not the fragment in the android.app package.
The activity that uses the fragment in the V4 package must inherit from the fragmentactivity.
In fact, using fragment is very similar to not using fragment earlier:
The first step is to put a viewpager component in the main layout file
The second step is to create a layout file for each page and write the interface well
The third step is to create a new fragment class for each page and load the interface in the layout file
The fourth part sets the adapter for viewpager, but the adapter here is not pageradapter, but instead
Fragmentpageradapter implements two methods:
Getcount(): returns the number of pages
Getitem (position): returns the fragment of the position position.
Let's take a look at an example of page sliding effect realized by viewpager and fragment:
First, inherit the fragmentactivity and provide the viewpager with the required fragment and fragmentpageradapter: fragment to specify the layout and function of the page
Adapter specifies how many pages the viewpager has and which page to display at that location:
Set onpagechangelistener to specify what other operations need to be done when changing the page:
Complete code:
The code manually sets the position of the page indicator by implementing the onpagechangelistener interface.