创建布局文件
activity_crime_pager.xml
<androidx.viewpager.widget.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_crime_pager_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.viewpager.widget.ViewPager>
创建CrimePagerActivity
public class CrimePagerActivity extends FragmentActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
}
}
ViewPager与PagerAdapter
RecyclerView 需借助于 Adapter 提供视图。同样地,ViewPager 也需要 PagerAdapter 的支持。我们使用PagerAdapter 的子类 FragmentStatePagerAdapter为ViewPager设置adapter。在 CrimePagerActivity 中,设置 ViewPager 的pager adapter,并实现它的 getCount() 和getItem(int) 方法:
CrimePagerActivity.onCreate(Bundle)
mViewPager = findViewById(R.id.activity_crime_pager_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
FragmentManager fragmentManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
@Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}
@Override
public int getCount() {
return mCrimes.size();
}
});
配置CrimePagerActivity
创建newIntent方法
CrimePagerActivity.java
private static final String EXTRA_CRIME_ID = "com.example.criminalintent.crime_id";
public static Intent newIntent(Context packageContext, UUID crimeID) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeID);
return intent;
}
配置启动CrimePagerActivity
CrimeListFragment.CrimeHolder.onClick(View)
@Override
public void onClick(View v) {
Intent intent = CrimePagerActivity.newIntent(getActivity(), mCrime.getId());
startActivity(intent);
}
修改配置文件
AndroidManifest.xml
<application
<!-- ... -->
<activity android:name=".CrimeListActivity">
<!-- ... -->
</activity>
<activity android:name=".CrimePagerActivity">
</activity>
</application>
设置初始分页显示项
CrimePagerActivity.java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
//...
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
Log.d(TAG, "当前显示的是第 " + i + " 条数据。");
mViewPager.setCurrentItem(i);
break;
}
}
}