就我而言,我想在视图中开始一些动画,但是使用setUserVisibleHint遇到了一些问题...
我的解决方案是:
1 /您的适配器的addOnPageChangeListener:
mViewPager.addOnPageChangeListener(this);
2 /实现OnPageChangeListener:
public class PagesFragment extends Fragment implements ViewPager.OnPageChangeListener
3 /覆盖3种方法:
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
@Override
public void onPageSelected(int position)
{
}
@Override
public void onPageScrollStateChanged(int state)
{
}
4 /在类上声明并初始化此变量
private static int mTabState = 1;
注意:我的适配器中有三个片段,并将mTabState用于setCurrentItem和适配器的当前位置,以识别哪个片段及时显示给用户... 5 / onPageSelected方法中添加以下代码:
if (mTabState == 0 || position == 0)
{
Intent intent = new Intent("animation");
intent.putExtra("current_position", position);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
}
如果上一页或当前页是页面0(片段在位置0),则执行此操作
6 /现在在您的片段类中(在适配器位置0的片段中),您必须创建广播接收器并在onResume方法中注册它,然后在onPause方法上注销它:
BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
if (Objects.equals(intent.getAction(), "animation"))
{
int currentPosition = intent.getIntExtra("current_position", 0);
if (currentPosition == 0)
{
startAnimation();
setViewsVisible();
} else
{
setViewsInvisible();
}
}
}
};
@Override
public void onResume()
{
super.onResume();
LocalBroadcastManager.getInstance(mContext).registerReceiver(broadcastReceiver, new IntentFilter("animation"));
}
@Override
public void onPause()
{
super.onPause();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(broadcastReceiver);
}
摘要:我有Fragment Pager Adapter巫婆在其中显示了三个片段,我想在Adapter位置0的Fragment中的视图上显示一些动画,为此,我使用BroadcastReceiver。拾取片段后,我将启动“动画”方法并向用户显示视图,而当片段未向用户显示时,我将尝试不可见视图...