Android Fragment 103

Using ViewPager, FragmentStatePagerAdapter vs FragmentPagerAdapter

ViewPager using Fragments

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ViewPager.ViewPagerActivity">

<androidx.viewpager.widget.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />

</androidx.constraintlayout.widget.ConstraintLayout>
public enum ModelObject {


RED(R.string.red, R.layout.view_red),
BLUE(R.string.blue, R.layout.view_blue),
GREEN(R.string.green, R.layout.view_green);

private int mTitleResId;
private int mLayoutResId;

ModelObject(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}

public int getTitleResId() {
return mTitleResId;
}

public int getLayoutResId() {
return mLayoutResId;
}

}
public class CustomPagerAdapter extends PagerAdapter {

private Context mContext;

public CustomPagerAdapter(Context context) {
mContext = context;
}

@Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}

@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}

@Override
public int getCount() {
return ModelObject.values().length;
}

@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}

@Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}

}
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new CustomPagerAdapter(this));

A Software Engineer and gamer at heart.