Skip to content
Advertisement

Simple swipe screen using VIewPager2 (Java)

I am trying to create layout which will show three screens which could be changed by swipe or by button. Between those buttons should be dots indicator of selected page.

I spent many time searching of samples how to do it, but usually I stucked on some issue. I don’t need option of dynamical adding of fragments. The best and working solution was thisone, but I wasn’t able to create three different fragments and it was missing the dots indicator.

Could someone help me with this issue? Thank you very much.

Advertisement

Answer

you can just have a new class that extends to FragmentStateAdapter and set the class as the adapter of your viewpager like so:

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

ViewPager2 viewPager2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewPager2 = findViewById(R.id.viewpager2);
    viewPager2.setAdapter(new ViewPagerFragmentAdapter(this));
}

static class ViewPagerFragmentAdapter extends FragmentStateAdapter {

    public ViewPagerFragmentAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        switch (position) {
            case 0:
                return new Vertical1();
            case 1:
                return new Vertical2();
            case 2:
                return new Vertical3();
        }
        return new Vertical2();
    }

    @Override
    public int getItemCount() {
        return 3;
    }
}

}

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement