There is a ViewPager with 3 fragments, which should scroll by pressing the buttons - left and right. I want the "left" button not to appear on Fragment1, all the buttons to appear on Fragment2, and the "right" button to not appear on Fragment three.

Before that, I did the same thing, only for 2 fragments:

final Button button2 = (Button) findViewById(R.id.button2); final Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { viewPager.setCurrentItem(0, true); button.setVisibility(View.INVISIBLE); button2.setVisibility(View.VISIBLE); } }); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { viewPager.setCurrentItem(1, true); button2.setVisibility(View.INVISIBLE); button.setVisibility(View.VISIBLE); } }); 

But how to make the same condition, but only for 3 fragments?

    1 answer 1

    You can get the index of the current fragment in the ViewPager using

     viewPager.getCurrentItem(); 

    And the number of items in the ViewPager using

     viewPager.getAdapter().getCount() 

    Then you can update the code responsible for the visibility of the buttons as follows:

     button2.setVisibility(viewPager.getCurrentItem() != 0? View.VISIBLE: View.INVISIBLE); //Кнопка, переключающая влево button.setVisibility(viewPager.getCurrentItem() != viewPager.getAdapter().getCount() - 1? View.VISIBLE: View.INVISIBLE); //Кнопка, переключающая вправо