5.2.4 Fragment Example - Bottom Navigation Bar + ViewPager for Page Swiping
Category Android Basic Tutorial
>
In the previous three sections, we implemented the effect of a regular bottom navigation bar in different ways, and in this section, we will add a ViewPager to the second example to implement the effect of page switching by swiping! Most friends should know what ViewPager is, but if you don't know, it doesn't matter, we will briefly introduce this control below!
1. Brief Introduction to ViewPager
1) What kind of control is it?
>
Answer: A page-switching component, we can fill it with multiple Views, and then we can switch different Views by swiping left and right on the screen. Like the ListView we learned before, we need an Adapter (Adapter) to bind the Views to be displayed with our ViewPager, and ViewPager has its own specific Adapter - PagerAdapter! In addition, Google officially recommends us to use Fragments to fill the ViewPager, which can more conveniently generate each Page and manage the lifecycle of each Page! Of course, it provides us with two different Adapters, they are: FragmentPageAdapter and FragmentStatePagerAdapter! What we will use in this section is the former: FragmentPageAdapter! In addition, it is worth mentioning that ViewPager's caching mechanism: ViewPager will cache the current page, the previous page, and the next page. For example, there are four pages: 1, 2, 3, 4: When we are on the first page: cache 1, 2
2) When using PagerAdapter, you need to override the relevant methods:
>
-getCount( ) : Get the number of views in the ViewPager
-destroyItem( ) : Remove a page at a given position. The adapter is responsible for removing this view from the container. This is to ensure that the view can be removed when finishUpdate(viewGroup) returns.
-instantiateItem( ) : ①Add the view at the given position to the ViewGroup (container), create and display it ②Return an Object (key) that represents the added page. Usually, you can directly return the view itself. Of course, you can also customize your own key, but the key and each view must correspond to each other
-isViewFromObject ( ): Determine whether the Key returned by the instantiateItem(ViewGroup, int) function and a page view represent the same view (i.e., whether they are corresponding, corresponding means the same View). Usually, we can simply write return view == object; it's okay, as to why it's more complicated to explain. Let's have a chance to understand later. It seems that there is an ArrayList in ViewPager that stores the state information of the view, and the corresponding information is retrieved according to the View!
PS: You don't have to override all methods~
2. Implementation effect and project directory structure:
Let's take a look at the effect we want to achieve first
Next, let's look at our project structure:
3. Code implementation:
Step 1: Preparation of related resource files:
PS: We are writing based on the method 2 of implementing the bottom navigation bar, so the resource files can be copied as they are! Here is not pasted multiple times ~!
Step 2: Write the layout file of activity_main.xml:
PS: Just replace the previous FrameLayout with: android.support.v4.view.ViewPager:
activity_mian.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="@+id/ly_top_bar"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@color/bg_topbar">
<TextView
android:id="@+id/txt_topbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:gravity="center"
android:text="Reminder"
android:textColor="@color/text_topbar"
android:textSize="18sp" />
<View
android:layout_width="match_parent"
android:layout_height="2px"
android:layout_alignParentBottom="true"
android:background="@color/div_white" />
</RelativeLayout>
<RadioGroup
android:id="@+id/rg_tab_bar"
android:layout_width="match_parent"
android
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fg_content, container, false);
TextView txt_content = (TextView) view.findViewById(R.id.txt_content);
txt_content.setText("First Fragment");
Log.e("HEHE", "1st Dog");
return view;
}
Just follow the example and make some changes!
### Step 4: Customizing the FragmentPagerAdapter class:
The code is quite simple, just pass a FragmentManager, and everything else is done here!
/**
- Created by Jay on 2015/8/31 0031. */ public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private final int PAGER_COUNT = 4;
private MyFragment1 myFragment1 = null;
private MyFragment2 myFragment2 = null;
private MyFragment3 myFragment3 = null;
private MyFragment4 myFragment4 = null;
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
myFragment1 = new MyFragment1();
myFragment2 = new MyFragment2();
myFragment3 = new MyFragment3();
myFragment4 = new MyFragment4();
}
@Override
public int getCount() {
return PAGER_COUNT;
}
@Override
public Object instantiateItem(ViewGroup vg, int position) {
return super.instantiateItem(vg, position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
System.out.println("position Destory" + position);
super.destroyItem(container, position, object);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case MainActivity.PAGE_ONE:
fragment = myFragment1;
break;
case MainActivity.PAGE_TWO:
fragment = myFragment2;
break;
case MainActivity.PAGE_THREE:
fragment = myFragment3;
break;
case MainActivity.PAGE_FOUR:
fragment = myFragment4;
break;
}
return fragment;
}
}
### Step 5: Writing MainActivity:
The logic is quite simple, just look at it yourself.
**MainActivity.java:**
package com.jay.fragmentdemo4;
import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView;
/**
- Created by Coder-pig on 2015/8/28 0028. */ public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, ViewPager.OnPageChangeListener {
//UI Objects
private TextView txt_topbar;
private RadioGroup rg_tab_bar;
private RadioButton rb_channel;
private RadioButton rb_message;
private RadioButton rb_better;
private RadioButton rb_setting;
private ViewPager vpager;
private MyFragmentPagerAdapter mAdapter;
//Constants representing pages
public static final int PAGE_ONE = 0;
public static final int PAGE_TWO = 1;
public static final int PAGE_THREE = 2;
public static final int PAGE_FOUR = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
bindViews();
rb_channel.setChecked(true);
}
private void bindViews() {
txt_topbar = (TextView) findViewById(R.id.txt_topbar);
rg_tab_bar = (RadioGroup) findViewById(R.id.rg_tab_bar);
rb_channel = (RadioButton) findViewById(R.id.rb_channel);
rb_message = (RadioButton) findViewById(R.id.rb_message);
rb_better = (RadioButton) findViewById(R.id.rb_better);
rb_setting = (RadioButton) findViewById(R.id.rb_setting);
rg_tab_bar.setOnCheckedChangeListener(this);
vpager = (ViewPager) findViewById(R.id.vpager);
vpager.setAdapter(mAdapter);
vpager.setCurrentItem(0);
vpager.addOnPageChangeListener(this);
}
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.rb_channel:
vpager.setCurrentItem(PAGE_ONE);
break;
case R.id.rb_message:
vpager.setCurrentItem(PAGE_TWO);
break;
case R.id.rb_better:
vpager.setCurrentItem(PAGE_THREE);
break;
case R.id.rb_setting:
vpager.setCurrentItem(PAGE_FOUR);
break;
}
}
//Override the ViewPager page change handling method
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
break; case PAGE_THREE: rb_better.setChecked(true); break; case PAGE_FOUR: rb_setting.setChecked(true); break; } } } ```
PS: Hehe, I also posted the package import part of the code above, just in case you import the wrong package and then encounter some inexplicable errors! Because ViewPager is under the v4 package, so Fragment, FragmentManager, FragmentTransaction all need to use the V4 package! In addition, the method to obtain FragmentManager is not to use getFragmentManager() directly but to use getSupportFragmentManager().
Note: If ViewPager is placed after RadioButton, the click event of RadioButton will be invalid.
4. Code Download:
FragmentDemo4: Download FragmentDemo4.zip
Summary of This Section:
>
Well, that's the process of implementing simple sliding switch Fragment with the bottom navigation bar + ViewPager! That's all, thank you~
1.8 Project Related Analysis (Various Files, Resource Access)
[2.4.6 Optimization of BaseAdapter](android-tutorial
4.4.2 Further Exploration of ContentProvider - Document Provider
5.2.1 Detailed Explanation of Fragment Examples - Implementation of Bottom Navigation Bar (Method 1)
5.2.2 Detailed Explanation of Fragment Examples - Implementation of Bottom Navigation Bar (Method 2)
5.2.3 Detailed Explanation of Fragment Examples - Implementation of Bottom Navigation Bar (Method 3)
5.2.4 Detailed Explanation of Fragment Examples - Bottom Navigation Bar + ViewPager for Page Swiping
6.2 Data Storage and Access - Saving User Preferences with SharedPreferences
6.3.1 Data Storage and Access - An Introduction to SQLite Database
6.3.2 Data Storage and Access - Another Look at SQLite Database
7.1.1 What to Learn in Android Network Programming and Studying the Http Protocol
7.1.2 Learning about Android Http Request and Response Headers
-10.10 Sensor Topic (1) – Introduction
-10.11 Sensor Topic (2) – Orientation Sensor
-10.12 Sensor Topic (3) – Accelerometer/Gyroscope Sensor
-10.12 Sensor Topic (4) – Other Sensors Overview
-10.14 Android GPS Introduction
-11.0 "2015 Latest Android Basic Tutorial" Concludes with Cheers~
-12.2 DrySister Girl Watching App (First Edition) – 2. Parsing Backend Data
-12.4 DrySister Girl Watching App (First Edition) – 4. Adding Data Caching (Integrating SQLite)