ViewPager中间嵌套ViewPager时,默认事件会被内部ViewPager拦截,当滑动到最左边或者最右边时,会被外部ViewPager接收,如下图所示:
现项目有一需求,要求内部ViewPager使用手动切换,左右滑动事件由外部ViewPager接收,待实现效果如下图所示:
解决方案
自定义内部ViewPager,拦截内部滑动事件,重写canScrollHorizontally
即可,直接返回false。
public class NoScrollViewPager extends ViewPager {
public NoScrollViewPager(@NonNull Context context) {
super(context);
}
public NoScrollViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean canScrollHorizontally(int direction) {
return false;
}
}
引用代码,布局全部使用java实现
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ViewPager contentView=new ViewPager(this);
setContentView(contentView);
final List<View> views = new ArrayList<>();
TextView view = new TextView(this);
ViewGroup.LayoutParams params=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
view.setLayoutParams(params);
//数据填充
view.setText("我是第一个TextView");
view.setGravity(Gravity.CENTER);
views.add(view);
final ViewPager viewPager=new NoScrollViewPager(this);
viewPager.setAdapter(new PagerAdapter() {
@Override
public int getCount() {
return 2;
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return view == o;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, final int position) {
TextView view = new TextView(MainActivity.this);
ViewGroup.LayoutParams params=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
view.setLayoutParams(params);
//数据填充
view.setText("我是第二个ViewPager——position:"+position);
view.setGravity(Gravity.CENTER);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
viewPager.setCurrentItem(position==0?1:0);
}
});
container.addView(view);
return view;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
});
views.add(viewPager);
PagerAdapter adapter = new PagerAdapter() {
@Override
public int getCount() {
return views.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
return view == o;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
View view = views.get(position);
container.addView(view);
return view;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
};
contentView.setAdapter(adapter);
}
}