当前位置: 代码迷 >> Android >> 在Android上的ViewPager中替换当前片段
  详细解决方案

在Android上的ViewPager中替换当前片段

热度:96   发布时间:2023-08-04 12:06:37.0

我有一个ViewPager ,如果某个动作发生,我必须替换第一个Fragment

public static class PagerAdapter extends FragmentStatePagerAdapter{

    private TempChannel latestChannel;
    private VideosFragment.SortType sortType;

    public PagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case 0:
                if(latestChannel == null) {
                    return new LatestVideosFragment();
                }else{
                    return VideosFragment.getVideosFragment(latestChannel, sortType);
                }
            case 1:
                return new LiveVideosFragment();
            case 2:
                return new ConversationsFragment();
        }
        return null;
    }
}

基本上,当我在LatestVideosFragment单击某个频道时,适配器中的第一个位置应该更改为VideosFragment类的实例。

public void startLatestChannelFragment(TempChannel channel, VideosFragment.SortType sortType){
    adapter.setLatestChannel(channel, sortType);
    adapter.notifyDataSetChanged();
    Log.d("x", "on channel started");
}

我假设在适配器上调用notifyDataSetChanged()会更新片段,但事实并非如此。 还尝试在ViewPager上调用invalidate( )而没有任何影响。 仅当我转到第三个选项卡然后返回第一个选项卡时,才会更新Fragment

在这里查看答案以获得一些好的解决方案:

基本上覆盖getItemPosition中的PagerAdapter将为您提供所需的效果。

public int getItemPosition(Object object) {
     return POSITION_NONE;
}
  相关解决方案