I have an old project written in Java made to slide horizontally between three different fragments, and they were stated on the main activity. It worked perfect.
public class MainActivity extends AppCompatActivity {
ViewPager pager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pager = findViewById(R.id.theViewPagerInTheMainActivity);
pager.setOffscreenPageLimit(3);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
Frag_A aFrag = new Frag_A();
adapter.addItem(aFrag);
Frag_B bFrag = new Frag_B();
adapter.addItem(bFrag);
Frag_C cFrag = new Frag_C();
adapter.addItem(cFrag);
pager.setAdapter(adapter);
pager.setCurrentItem(1);
}
class PagerAdapter extends FragmentStatePagerAdapter {
ArrayList<Fragment> items = new ArrayList<Fragment>();
public PagerAdapter(FragmentManager fragManager) {
super(fragManager);
}
public void addItem(Fragment item) {
items.add(item);
}
@Override
public Fragment getItem(int position) {
return items.get(position);
}
@Override
public int getCount() {
return items.size();
}
}
}
Each three different fragments, followed by different codes that works fine, starts with:
public class Frag_A extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag_a, container, false);
}
}
Same goes like Frag_B and frag_b layout, Frag_C and frag_c layout.
I'm doing it all again now, but in Kotlin and using ViewPager2. I'm not making any fragments programmatically, I want all three of their ID written on the main activity. Converting the code directly in Android Studio didn't work, of course, and hours of searching failed to cover my needs. From my humble understanding, creating different-coloured fragments from one pre-made fragment doesn't really seem to be adaptable for my project and all ended up in red underlines. Can it be made without importing .v4 supporting library?
Solved by myself!