Here are some summaries of fragments and ViewPager. As for the Fragment and ViewPager, they are usually used together. They can be used to swipe left or right like QQ or wechat. See the GIF below.
All right, now let’s start talking about how to use them.
Fragment
We customize a system-modify Fragment class for shameshameFragment that inherits Fragment with the following code:
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragement_recommend, container, false); }}Copy the code
System-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system-system.html
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recommend_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF4F4F4"
android:overScrollMode="never" />
</RelativeLayout>
Copy the code
Fragments can be created using simple factory mode as follows:
/ * * *@author JonesYang
* @DataThe 2020-10-17 *@FunctionCreate fragments * /
public class FragmentCreator {
// represents the different factory types
public static final int INDEX_RECOMMEND = 0;
public static final int INDEX_SUBSCRIPTION = 1;
public static final int INDEX_HISTORY = 2;
// The number of fragments
public static final int PAGE_COUNT = 3;
// Use a Map collection to cache the Fragment
private static Map<Integer, BaseFragment> sCache = new HashMap<>();
// Get the Fragment method
public static BaseFragment getFragment(int index) {
// Search for the Fragment in the cache. If it exists in the cache, return the Fragment
BaseFragment fragment = sCache.get(index);
if(fragment ! =null) {
return fragment;
}
// If no Fragment exists in the cache
switch (index) {
case INDEX_RECOMMEND:
fragment = new RecommendFragment();
break;
case INDEX_SUBSCRIPTION:
fragment = new SubscriptionFragment();
break;
case INDEX_HISTORY:
fragment = new HistoryFragment();
break;
}
// Add the Fragment to the Map cache
sCache.put(index, fragment);
returnfragment; }}Copy the code
ViewPager
ViewPager does the following:
- The ViewPager is mainly used for swiping left and right. (Similar to picture rotation)
- The ViewPager uses an adapter to connect the “view” and “data.” (You can think of the listView use method, the principle is similar)
- ViewPager is officially recommended for use with fragments and has a dedicated adapter.
A ViewPager needs to use an adapter. For example, use the Fragment + ViewPager adapter.
Fragment + ViewPager
First, with a single Fragment, the Activity must inherit from the FragmentActivity class. Look at the adapter. The adapter must inherit from the FragmentPagerAdapter:
/ * * *@author JonesYang
* @DataThe 2020-10-17 *@FunctionViewPager + Fragment adapter */
public class MainContentAdapter extends FragmentPagerAdapter {
public MainContentAdapter(FragmentManager manager) {
super(manager);
}
@NonNull
@Override
public Fragment getItem(int position) {
// Return the Fragment retrieved
return FragmentCreator.getFragment(position);
}
@Override
public int getCount(a) {
// Return the number of fragments
returnFragmentCreator.PAGE_COUNT; }}Copy the code
The XML file corresponding to the Activity contains a ViewPager control like this:
<androidx.viewpager.widget.ViewPager
android:id="@+id/content_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/magic_indicator"
android:overScrollMode="never" />
Copy the code
In an Activity that inherits the FragmentActivity class, the adapter is used like this:
// Get the ID of the ViewPager control
viewPager = findViewById(R.id.content_pager);
/ / get FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
// Define the adapter with the FragmentManager parameter
MainContentAdapter contentAdapter = new MainContentAdapter(manager);
// Set the adapter for ViewPager
viewPager.setAdapter(contentAdapter);
Copy the code
Fragment + ViewPager is used to slide multiple fragments left and right. In fact, we need more than that. As shown in the GIF, we need to implement two functions:
- Click on the title above and the Fragment in the ViewPager below will change.
- Swipe left and right, and the title of the Table bar will slide along.
For the first function, we go to the title control and set the click event with the following line:
viewPager.setCurrentItem(int position); // Just pass in the Fragment's position
Copy the code
For the second function, we need to implement onPageScrollStateChanged interface, which has the following source code:
public interface OnPageChangeListener { /** * This method will be invoked when the current page is scrolled, either as part * of a programmatically initiated smooth scroll or a user initiated touch scroll. * * @param position Position index of the first page currently being displayed. * Page position+1 will be visible if positionOffset is nonzero. * @param positionOffset Value from [0, 1) indicating the offset from the page at position. * @param positionOffsetPixels Value in pixels indicating the offset from position. */ void onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels); /** * This method will be invoked when a new page becomes selected. Animation is not * necessarily complete. * * @param position Position index of the new selected page. */ void onPageSelected(int position); /** * Called when the scroll state changes. Useful for discovering when the user * begins dragging, when the pager is automatically settling to the current page, * or when it is fully stopped/idle. * * @param state The new scroll state. * @see ViewPager#SCROLL_STATE_IDLE * @see ViewPager#SCROLL_STATE_DRAGGING * @see ViewPager#SCROLL_STATE_SETTLING */ void onPageScrollStateChanged(int state); }Copy the code
Let’s talk about it briefly.
- OnPageScrollStateChanged (int state) : There are three states, SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, and SCroll_state_EXPLAINED, which respectively indicate that the sliding has not started, is in progress, or is completed.
- Void onPageScrolled(int position, float positionOffset, @px int positionOffsetPixels) : Trigger this method continuously during sliding.
- Void onPageSelected(int position) : The slide has been completed. Position indicates the current position.
We just need to rewrite the above three methods to implement the second function of appeal.