Challenge #2 (first and last)


#1

It’s not the prettiest solution but it works like it’s supposed to. I guess there must be a more concise way to do this. Would love your thoughts:

public class CrimePagerActivity extends AppCompatActivity implements View.OnClickListener {

private static final String EXTRA_CRIME_ID =
        "com.bignerdranch.android.criminalintent.crime_id";

private ViewPager mViewPager;
private List<Crime> mCrimes;
private Button mFirst, mLast;

public static Intent newIntent(Context packageContext, UUID crimeId) {
    Intent intent = new Intent(packageContext, CrimePagerActivity.class);
    intent.putExtra(EXTRA_CRIME_ID, crimeId);
    return intent;
}

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

    UUID crimeId = (UUID) getIntent()
            .getSerializableExtra(EXTRA_CRIME_ID);

    mViewPager = findViewById(R.id.crime_view_pager);
    mFirst = findViewById(R.id.btn_first);
    mLast = findViewById(R.id.btn_last);

    mCrimes = CrimeLab.get(this).getCrimes();

    FragmentManager fragmentManager = getSupportFragmentManager();
    mViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {

        @Override
        public Fragment getItem(int position) {
            Crime crime = mCrimes.get(position);

            if(mViewPager.getCurrentItem() == 0){
                mFirst.setEnabled(false);
            } else {
                mFirst.setEnabled(true);
            }
            if(mViewPager.getCurrentItem() == mCrimes.size() - 1){
                mLast.setEnabled(false);
            } else {
                mLast.setEnabled(true);
            }

            return CrimeFragment.newInstance(crime.getId());
        }

        @Override
        public int getCount() {
            return mCrimes.size();
        }
    });

    for (int i = 0; i < mCrimes.size(); i++) {
        if (mCrimes.get(i).getId().equals(crimeId)) {
            mViewPager.setCurrentItem(i);
            break;
        }

    }

    mFirst.setOnClickListener(this);
    mLast.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_first:
            mViewPager.setCurrentItem(0);
            break;
        case R.id.btn_last:
            mViewPager.setCurrentItem(mCrimes.size() - 1);
            break;
        default:
            break;
    }
}

}