采用Viewpager+Fragment实现
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class FragmentAdapter<F extends Fragment> extends FragmentPagerAdapter {
private final List<F> mFragmentSet = new ArrayList<>();
private F mCurrentFragment;
private ViewPager mViewPager;
public BaseFragmentAdapter(FragmentManager fm) {
super(fm);
}
@SuppressWarnings("unchecked")
@Override
public void setPrimaryItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
if (getCurrentFragment() != object) {
// 记录当前的Fragment对象
mCurrentFragment = (F) object;
}
super.setPrimaryItem(container, position, object);
}
public void addFragment(F fragment) {
mFragmentSet.add(fragment);
}
@Override
public void startUpdate(@NonNull ViewGroup container) {
super.startUpdate(container);
if (container instanceof ViewPager) {
// 记录绑定 ViewPager
mViewPager = (ViewPager) container;
}
}
public void setCurrentItem(int position) {
if (mViewPager != null) {
mViewPager.setCurrentItem(position);
}
}
public void setCurrentItem(int position, boolean smoothScroll) {
if (mViewPager != null) {
mViewPager.setCurrentItem(position, smoothScroll);
}
}
------------------- 此处更多代码略 -------------------
}
BaseFragmentAdapter mPagerAdapter = new BaseFragmentAdapter<>(getSupportFragmentManager());
mPagerAdapter.addFragment(new FragmentA());
mPagerAdapter.addFragment(new FragmentB());
mPagerAdapter.addFragment(new FragmentC());
mPagerAdapter.addFragment(new FragmentD());
ViewPager mViewPager ;
mViewPager .setAdapter(mPagerAdapter);
// 限制页面数量
mViewPager .setOffscreenPageLimit(mPagerAdapter.getCount());
网友评论