我正在使用自定义ViewPager,当我滑动到新页面时,ViewPager.OnPageChangeListener不起作用。可能是什么原因?
mPager = (WrapContentHeightViewPager) findViewById(R.id.pager);
mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.
currentFav = position;
Log.i("currentFav pos", currentFav+"");
}
});
答案 0 :(得分:10)
我正在使用ViewPagerIndicator库,所以根据这个库,我应该将页面监听器设置为指示器。
mIndicator.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
doYourThing();
}
});
更新@ powder366:
在build.gradle文件中,将库添加到依赖项
compile 'com.viewpagerindicator:library:2.4.1@aar'
在您的顶级build.gradle文件中,添加以下内容:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
maven { url "http://dl.bintray.com/populov/maven" }
mavenCentral()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
maven { url "http://dl.bintray.com/populov/maven" }
mavenCentral()
jcenter()
}
}
您可以将指标添加到xml中,如下所示:
<com.viewpagerindicator.CirclePageIndicator
android:id="@+id/indicator"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/blue"
android:padding="10dip"
app:fillColor="@color/circleindicatorfill"
app:pageColor="@color/circleindicatorempty"
app:strokeWidth="0dp" />
获取指标如下:
mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
mViewPager.setAdapter(mFragmentAdapter);
mIndicator.setViewPager(mViewPager);
mIndicator
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position,
float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
// Check if this is the page you want.
/* currentFav = position;
Log.i("currentFav pos", currentFav + "");*/
}
});