Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get fragment by tag or id from tablayout ,android

i use this tutorial for creating tab. and now i have a recyclerview in each fragment and i want to notify them from mainactivity. how to access the adapter in fragment?

i use this for calling refreshData() method in fragment:

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

but that return null.

mainActivity:

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) {

    }
});

PagerAdapter:

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;
}
}

One of 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);
    }

The CardAdapter:

  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);
    }
}
}
like image 456
javadroid Avatar asked Aug 08 '15 07:08

javadroid


2 Answers

EDIT: After many test, the previous answer work with Android < 21, but for Android > 21 it's little bit weird, it doesn't seems to work in the same way.

Finally, I solved it like that, and it works everywhere:

In your adapter:

    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);
}

And you call getFragment where you want in your activity like that:

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

PREVIOUS ANSWER :

Warning : it doesn't really work with Android > 21


I had the same problem. Finally, i did'nt use id or tag.

Instead of using:

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

use this:

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

to get instance of CustomFragment.

I have put get(0) as your position of CustomFragment instance is at zero.

I found this issue here: Set and get using tag a fragment in android

like image 165
Benjamin Lucidarme Avatar answered Nov 03 '22 01:11

Benjamin Lucidarme


This is late but I hope this will be helpful for someone. To find fragment by tag we can do this:

String tag=getSupportFragmentManager().getFragments().get(index).getTag();
SecondFragment f = (SecondFragment) getSupportFragmentManager().findFragmentByTag(tag);
like image 40
Ali Aslam Avatar answered Nov 03 '22 01:11

Ali Aslam