Trước khi đi vào ví dụ, chúng ta nên biết ViewPager là gì trong Android. ViewPager nằm trong Support Library, sử dụng ViewPager chúng ta có thể chuyển đổi giữa các Fragment.
Ví dụ này minh họa cách sử dụng Android ViewPager.
Bước 1
Tạo một dự án mới trong Android Studio, vào File → New Project và điền đầy đủ thông tin cần thiết để tạo dự án mới.
Bước 2
Thêm mã sau vào build.gradle.
apply plugin: 'com.android.application' android { compileSdkVersion 28 defaultConfig { applicationId "com.example.andy.myapplication" minSdkVersion 19 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support:design:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' }Bước 3
Thêm mã sau vào res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android = "https://schemas.android.com/apk/res/android" xmlns:app = "https://schemas.android.com/apk/res-auto" android:layout_width = "match_parent" android:layout_height = "match_parent"> <android.support.design.widget.AppBarLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:theme = "@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.v7.widget.Toolbar android:id = "@+id/toolbar" android:layout_width = "match_parent" android:layout_height = "?attr/actionBarSize" android:background = "?attr/colorPrimary" app:layout_scrollFlags = "scroll|enterAlways" app:popupTheme = "@style/ThemeOverlay.AppCompat.Light" /> <android.support.design.widget.TabLayout android:id = "@+id/tabs" android:layout_width = "match_parent" android:layout_height = "wrap_content" app:tabMode = "fixed" app:tabGravity = "fill"/> </android.support.design.widget.AppBarLayout> <android.support.v4.view.ViewPager android:id = "@+id/viewpager" android:layout_width = "match_parent" android:layout_height = "match_parent" app:layout_behavior = "@string/appbar_scrolling_view_behavior" /> </android.support.design.widget.CoordinatorLayout>
Bước 4
Thêm mã sau vào src/MainActivity.java
package com.example.andy.myapplication; import android.annotation.TargetApi; import android.os.Build; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private ViewPager viewPager; private Toolbar toolbar; private TabLayout tabLayout; @TargetApi(Build.VERSION_CODES.O) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); tabLayout = findViewById(R.id.tabs); viewPager = findViewById(R.id.viewpager); ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new OneFragment(), "ONE"); adapter.addFragment(new TwoFragment(), "TWO"); viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); } class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> mList = new ArrayList<>(); private final List<String> mTitleList = new ArrayList<>(); public ViewPagerAdapter(FragmentManager supportFragmentManager) { super(supportFragmentManager); } @Override public Fragment getItem(int i) { return mList.get(i); } @Override public int getCount() { return mList.size(); } public void addFragment(Fragment fragment, String title) { mList.add(fragment); mTitleList.add(title); } @Override public CharSequence getPageTitle(int position) { return mTitleList.get(position); } } }Bước 5
Thêm mã sau vào src/OneFragment.java
package com.example.andy.myapplication; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class OneFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View v= inflater.inflate(R.layout.fragment_one, container, false); TextView textView=v.findViewById(R.id.text); textView.setText("First Fragment"); return v; } }Bước 6
Thêm mã sau vào src/TwoFragment.java
package com.example.andy.myapplication; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class TwoFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View v= inflater.inflate(R.layout.fragment_one, container, false); TextView textView=v.findViewById(R.id.text); textView.setText("Second Fragment"); return v; } }Bước 7
Thêm mã sau vào res/layout/fragment_one.xml.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textSize="20sp" /> </LinearLayout>
Bước 8
Thêm mã sau vào styles.xml.
<resources> <!-- Base application theme. --> <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name = "windowNoTitle">true</item> <item name = "windowActionBar">false</item> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> </resources>
Hãy thử chạy ứng dụng. Giả sử bạn đã kết nối thiết bị Android thực tế với máy tính. Để chạy ứng dụng từ Android Studio, mở một file activity của dự án và nhấn biểu tượng Run từ thanh công cụ. Chọn thiết bị di động của bạn làm tùy chọn và kiểm tra thiết bị sẽ hiển thị màn hình mặc định:

