观察者方法没有被调用。我以传统的方式测试了ViewPagerCycler
,并且工作完美。感谢帮助。
public final class ViewPagerCycler implements LifecycleObserver {
private static final int PERIOD = 3000;
private Timer mTimer;
private TimerTask mTask;
private Activity mActivity;
private ViewPager mPager;
public ViewPagerCycler(Activity activity, ViewPager pager) {
mActivity = activity;
mPager = pager;
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void start() {
int count = mPager
.getAdapter()
.getCount();
mTimer = new Timer();
mTask = new TimerTask() {
@Override public void run() {
mActivity.runOnUiThread(new TimerTask() {
@Override public void run() {
mPager.setCurrentItem((mPager.getCurrentItem() + 1) % count, true);
}
});
}
};
mTimer.schedule(mTask, PERIOD, PERIOD);
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void stop() {
mTask.cancel();
mTimer.cancel();
mTimer.purge();
}
}
Activity 刚刚总结。我没有添加
findViewById
。public class SummariziedActivity extends Activity implements LifecycleOwner {
private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
@Override protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRegistry.addObserver(new ViewPagerCycler(mPager));
}
}
在
build.gradle
中:compile "android.arch.lifecycle:runtime:1.0.0-alpha2"
compile "android.arch.lifecycle:extensions:1.0.0-alpha2"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha2"
最佳答案
您应该从Activity
扩展,而不是扩展普通的LifecycleActivity
。
否则,您可以引用"Implementing LifecycleOwner in custom activities and fragments":
public class MyFragment extends Fragment implements LifecycleRegistryOwner { LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this); @Override public LifecycleRegistry getLifecycle() { return lifecycleRegistry; } }