Sliding between fragments using Viewpager2 and Kotlin

2.2k views Asked by At

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?

2

There are 2 answers

1
Tongireth On BEST ANSWER

Solved by myself!

class MainActivity : FragmentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val adapter = DatPagerAdapter(this)
    val fragsList = listOf(Frag_A(), Frag_B(), Frag_C())
    adapter.fragsListHere.addAll(fragsList)
    theVP2InTheMainActivity.adapter = adapter
    theVP2InTheMainActivity.setCurrentItem(1)
  }
  class DatPagerAdapter(fragactivity: FragmentActivity) : FragmentStateAdapter(fragactivity) {
    val fragsListHere = mutableListOf<Fragment>()
    override fun getItemCount():Int = fragListHere.size
    override fun createFragment(position: Int): Fragment = fragListHere[position]
  }
}
0
Marouan Akechtah On

Since FragmentPagerAdapter is depecrated. I switch it to FragmentStateAdapter(FragmentActivity fragmentActivity) that work fine with ViewPager2

My ViewPagerAdapter :

``` 
    class ViewPagerAdapter(fragmentActivity: FragmentActivity): 
    FragmentStateAdapter(fragmentActivity){

    override fun getItemCount(): Int {
        return 3
    }

    override fun createFragment(position: Int): Fragment {
        return when(position){
            0 -> {
                HomeFragment()
            }
            1 -> {
                HomeFragment2()
            }
            2 -> {
                HomeFragment3()
            }
            else -> {
                throw Resources.NotFoundException("Position Not Found")
            }
        }
    }
}
```

My Activity :

    class MainActivity5 : AppCompatActivity() {
    
        private lateinit var binding: ActivityMain5Binding
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivityMain5Binding.inflate(layoutInflater)
            val view = binding.root
            setContentView(view)
    
            binding.viewpager.adapter = ViewPagerAdapter(this)
    
        }
        // If the user is currently looking at the first step, allow the system to handle the
        // Back button. This calls finish() on this activity and pops the back stack.

    override fun onBackPressed() {
        if (binding.viewpager.currentItem == 0) {
            super.onBackPressed()
        } else {
            // Otherwise, select the previous step.
            binding.viewpager.currentItem = binding.viewpager.currentItem - 1
        }
    }
    }

Thanks For asking!! Note: I used binding to replace findViewById