Я попытался использовать onPageScrolled
, но у меня возникла проблема на стадии вызова .addOnPageChangeListener
Возможно здесь нужно использовать не .addOnPageChangeListener
, а что-то иное, тогда подскажите что именно использовать.
Вот код из MainActivity.java:
import android.os.Bundle;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
public class MainActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 6;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager2 viewPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private FragmentStateAdapter pagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager2 and a PagerAdapter.
viewPager = findViewById(R.id.pager);
pagerAdapter = new ScreenSlidePagerAdapter(this);
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { //Здесь и возникает ошибка
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Toast.makeText(getApplicationContext(), "Выбран " + position,
Toast.LENGTH_LONG).show();
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
@Override
public void onBackPressed() {
if (viewPager.getCurrentItem() == 0) {
// 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.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
/**
* A simple pager adapter that represents 6 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStateAdapter {
public ScreenSlidePagerAdapter(FragmentActivity fa) {
super(fa);
}
@Override
public Fragment createFragment(int position) {
return new fragment_screen_slide_page();
}
@Override
public int getItemCount() {
return NUM_PAGES;
}
}
}