要求某种情况下ViewPager和TabLayout取消滑动保留点击,那么我们只需要重写这个方法就可以禁止ViewPager滑动就行了
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class NoSrcollViewPage extends ViewPager {
private boolean isCanScroll = false;
public NoSrcollViewPage(Context context) {
super(context);
}
public NoSrcollViewPage(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setScanScroll(boolean isCanScroll) {
this.isCanScroll = isCanScroll;
}
@Override
public void scrollTo(int x, int y) {
super.scrollTo(x, y);
}
@Override
public boolean onTouchEvent(MotionEvent arg0) {
// TODO Auto-generated method stub
if (isCanScroll) {
return super.onTouchEvent(arg0);
} else {
return false;
}
}
@Override
public void setCurrentItem(int item, boolean smoothScroll) {
// TODO Auto-generated method stub
super.setCurrentItem(item, smoothScroll);
}
@Override
public void setCurrentItem(int item) {
// TODO Auto-generated method stub
super.setCurrentItem(item);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
// TODO Auto-generated method stub
if (isCanScroll) {
return super.onInterceptTouchEvent(arg0);
} else {
return false;
}
}
}
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private NoSrcollViewPage vp;
private List<String> titles=new ArrayList<>();
private List<Fragment> fragments=new ArrayList<>();
private TabLayout tab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
titles.add("aaaa");
titles.add("bbbb");
titles.add("cccc");
titles.add("dddd");
titles.add("eeee");
titles.add("ffff");
vp = (NoSrcollViewPage) findViewById(R.id.searchglobal_viewpager);
tab = (TabLayout) findViewById(R.id.searchglobal_tablayout);
for (int i = 0; i < titles.size(); i++) {
NoScrollFragment noScrollFragment = NoScrollFragment.createNoScrollFragment(i);
fragments.add(noScrollFragment);
}
MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
vp.setAdapter(adapter);
tab.setupWithViewPager(vp);
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments!=null?fragments.size():0;
}
@Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
}