I thought of the same solution at first but i am facing an issue with getItem() as i does get called each time and i still don’t know why so i used ViewPager method addOnPageChangeListener()
Hello @pat, your solution seems absolutely correct. what I did not understand is I tried to get position from CrimeListFragment intent and passed it to CrimePagerActivity and checked that position for 0 or list size -1 and then disabled the buttons because buttons are outside the viewPager and in the Activity.
and it worked when I put the logic inside the viewPager, setAdapter method like yours.
public class CrimePagerActivity extends AppCompatActivity {
private static final String EXTRA_CRIME_ID = "crime_id";
private static final String POSITION ="clicked_position";
private ViewPager mViewPager;
private List<Crime> mCrimeList;
private Button mFirstBtn, mLastBtn;
public static Intent newIntent(Context packageContext, UUID crimeId, int position) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
intent.putExtra(POSITION, position);
return intent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
mFirstBtn = findViewById(R.id.jumpToFirst_btn);
mLastBtn = findViewById(R.id.jumpToLast_btn);
mViewPager = findViewById(R.id.crime_view_pager);
mCrimeList = CrimeLab.get(this).getCrimes();
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
int position = getIntent().getIntExtra(POSITION,0);
if(position==0){
mFirstBtn.setEnabled(false);
}else{
mFirstBtn.setEnabled(true);
}
if(position==mCrimeList.size()-1){
mLastBtn.setEnabled(false);
}else{
mLastBtn.setEnabled(true);
}
mFirstBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mViewPager.setCurrentItem(0);
}
});
mLastBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mViewPager.setCurrentItem(mCrimeList.size()-1);
}
});
FragmentManager fragmentManager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
@Override
public Fragment getItem(int position) {
Crime crime = mCrimeList.get(position);
// if(mViewPager.getCurrentItem()==0){
// mFirstBtn.setEnabled(false);
// }else{
// mFirstBtn.setEnabled(true);
// }
//
// if(mViewPager.getCurrentItem()==mCrimeList.size()-1){
// mLastBtn.setEnabled(false);
// }else{
// mLastBtn.setEnabled(true);
// }
return CrimeFragment.newInstance(crime.getId());
}
@Override
public int getCount() {
return mCrimeList.size();
}
});
for (int i = 0; i < mCrimeList.size(); i++) {
if (mCrimeList.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}