从 tablayout 中按标签或 id 获取片段,android

get fragment by tag or id from tablayout ,android

我使用 this tutorial 创建选项卡。 现在我在每个片段中都有一个 recyclerview,我想从 mainactivity 通知他们。如何访问片段中的适配器?

我用它来调用片段中的 refreshData() 方法:

  TabFragment1 tabFragment = (TabFragment1) getSupportFragmentManager().findFragmentByTag(TabFragment1.class.getSimpleName());
 if (tabFragment != null) {
                    tabFragment.refreshData();
                } 

但是 return 无效。

主要活动:

TabLayout     tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab2"));


final PagerAdapter adapter = new PagerAdapter
        (getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
});

寻呼机适配器:

public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;

public PagerAdapter(FragmentManager fm, int NumOfTabs) {
    super(fm);
    this.mNumOfTabs = NumOfTabs;
}

@Override
public Fragment getItem(int position) {

    switch (position) {
        case 0:
            TabFragment1 tab1 = new TabFragment1();
            return tab1;
        case 1:
            TabFragment2 tab2 = new TabFragment2();
            return tab2;
        case 2:
            TabFragment3 tab3 = new TabFragment3();
            return tab3;
        case 3:
            TabFragment4 tab4 = new TabFragment4();
            return tab4;
        default:
            return null;
    }
}

@Override
public int getCount() {
    return mNumOfTabs;
}
}

myTabFragment之一:

 public CardAdapter adapter;
       @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        RecyclerView v = (RecyclerView) inflater.inflate(R.layout.tab_fragment_1, container, false);
        SetupRecycleView(v);
        return v;
    }
  public void refreshData() {
        adapter.notifyDataSetChanged();

    }
    void SetupRecycleView(RecyclerView recList) {
        recList.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(G.context);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        //recList.setLayoutManager(new GridLayoutManager(G.context, 2));
        recList.setLayoutManager(llm);
        List<StructGhaza> ghazas = StructGhaza.getAllGhaza("2");
        adapter = new CardAdapter(ghazas);
        recList.setAdapter(adapter);
    }

卡适配器:

  public class CardAdapter extends     RecyclerView.Adapter<CardAdapter.GhazaViewHolder> {

private List<StructGhaza> ghazas;

public CardAdapter(List<StructGhaza> ghazaList) {
    this.ghazas = ghazaList;
}

@Override
public int getItemCount() {
    return ghazas.size();
}

@Override
public void onBindViewHolder(GhazaViewHolder ghazaViewHolder, int position) {

    StructGhaza ghaza = ghazas.get(position);
    ghazaViewHolder.vTitle.setText(ghaza.Name);
    //----Load Image
    Glide.with(G.context)
            .load(ghaza.Aks)
            .placeholder(R.drawable.loading_spinner)
            .crossFade()
            .into(ghazaViewHolder.itemImg);
    //---------------
    ghazaViewHolder.Rate.setRating(ghaza.Star);
    ghazaViewHolder.sampleLayout.setHoverView(ghazaViewHolder.hover);
    ghazaViewHolder.sampleLayout.addChildAppearAnimator(ghazaViewHolder.hover, R.id.tvHover, Techniques.FlipInX);
    ghazaViewHolder.sampleLayout.addChildDisappearAnimator(ghazaViewHolder.hover, R.id.tvHover, Techniques.FlipOutX);
}

@Override
public GhazaViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View itemView = LayoutInflater.
            from(viewGroup.getContext()).
            inflate(R.layout.fragment_carditem, viewGroup, false);

    return new GhazaViewHolder(itemView);
}

public static class GhazaViewHolder extends RecyclerView.ViewHolder {
    protected TextView vTitle;
    protected BlurLayout sampleLayout;
    protected View hover;
    protected ImageView itemImg;
    protected RatingBar Rate;

    public GhazaViewHolder(View v) {
        super(v);
        sampleLayout = (BlurLayout) v.findViewById(R.id.sample);
        itemImg = (ImageView) v.findViewById(R.id.item_img);
        hover = LayoutInflater.from(G.context).inflate(R.layout.fragment_hover, null);
        vTitle = (TextView) v.findViewById(R.id.titleTv);
        Rate = (RatingBar) v.findViewById(R.id.rating);
    }
}
}

编辑: 经过多次测试,之前的答案适用于 Android < 21,但对于 Android > 21 有点奇怪,它似乎无法以相同的方式工作。

最后我就这样解决了,到处都行:

在您的适配器中:

    HashMap<Integer, Fragment> mPageReferenceMap = new HashMap<>();
@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment fragment = (Fragment) super.instantiateItem(container, position);
    mPageReferenceMap.put(position, fragment);
    return fragment;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    super.destroyItem(container, position, object);
    mPageReferenceMap.remove(position);
}
public Fragment getFragment(int key) {
    return mPageReferenceMap.get(key);
}

然后你在 activity 中你想要的地方调用 getFragment 就像这样:

int index = viewPager.getCurrentItem();
ViewPagerAdapter adapter = ((ViewPagerAdapter)viewPager.getAdapter());
final YourFragment tabFragment = (YourFragment) adapter.getFragment(index);

上一个答案:

警告:它不适用于 Android > 21


我遇到了同样的问题。最后,我没有使用 id 或 tag。

而不是使用:

CustomFragment customFragment = (CustomFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.fragment_custo_tag));

使用这个:

CustomFragment customFragment = (CustomFragment) getSupportFragmentManager().getFragments().get(0);

获取 CustomFragment 的实例。

我已将 get(0) 作为您的 CustomFragment 实例的位置为零。

我在这里发现了这个问题:

来晚了,但我希望这对某人有所帮助。 要通过标签查找片段,我们可以这样做:

String tag=getSupportFragmentManager().getFragments().get(index).getTag();
SecondFragment f = (SecondFragment) getSupportFragmentManager().findFragmentByTag(tag);