在tabHost下,由于重写了onCreateView,保存fragment实例,导致了Tab切换时,ConvenientBanner在最后一张图准备轮播到第一张图,会出现空白。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (rootView == null) {
rootView = inflater.inflate(layoutInit(), container, false);
}
// 缓存的rootView需要判断是否已经被加过parent,如果有parent需要从parent删除,要不然会发生这个rootview已经有parent的错误。
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
return rootView;
}
找了很久没有找到原因,后面找到一个偏门的解决方法,在切换TAB之前将currentItem设为0。
解决代码:
public class ConvenientBanner<T> extends LinearLayout {
*****************************省略其他代码************************
/***
* 开始翻页(第一次翻页)
*
* @param autoTurningTime
* 自动翻页时间
* @return
*/
public ConvenientBanner startTurning(long autoTurningTime) {
// 如果是正在翻页的话先停掉
if (turning) {
stopTurning();
}
// 初始化page(否则在tabhost中会出现白屏)
viewPager.setCurrentItem(0);
// 设置可以翻页并开启翻页
canTurn = true;
this.autoTurningTime = autoTurningTime;
turning = true;
timeHandler.postDelayed(adSwitchTask, autoTurningTime);
return this;
}
/***
* 重新开始翻页(手指触碰暂停翻页,松开之后的重新翻页,不需要setItem为0)
*
* @param autoTurningTime
* 自动翻页时间
* @return
*/
public ConvenientBanner reStartTurning(long autoTurningTime) {
// 如果是正在翻页的话先停掉
if (turning) {
stopTurning();
}
// 设置可以翻页并开启翻页
canTurn = true;
this.autoTurningTime = autoTurningTime;
turning = true;
timeHandler.postDelayed(adSwitchTask, autoTurningTime);
return this;
}
// 触碰控件的时候,翻页应该停止,离开的时候如果之前是开启了翻页的话则重新启动翻页
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP) {
// 重新开始翻页
if (canTurn)
reStartTurning(autoTurningTime);
} else if (ev.getAction() == MotionEvent.ACTION_DOWN) {
// 停止翻页
if (canTurn)
stopTurning();
}
return super.dispatchTouchEvent(ev);
}
}
如果有朋友能找到根本原因,希望能给我留言,谢谢。