Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set and get using tag a fragment in android

I've created a tab layout with viewpager. Everything was alright, except that I need to run a method in a specific moment. So I need to get fragment instance and run their method. I create in this way:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    activateToolbarWithNavigationView(HomeActivity.this);
    // Tabs Setup
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    final ViewPager viewPager = (ViewPager) findViewById(R.id.home_pager);
    if (tabLayout != null) {
        tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.favorites_label_fragment)).setTag(getString(R.string.fragment_favorite_tag)));
        tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.air_today_label_fragment)).setTag(getString(R.string.fragment_airing_today_tag)));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        final HomePageAdapter adapter = new HomePageAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount());
        if (viewPager != null) {
            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 void refreshFavorites(){
    FavoritesFragment favoritesFragment = (FavoritesFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.fragment_favorite_tag));
    if(favoritesFragment != null) favoritesFragment.executeFavoriteList();
}

I don't know if i'm doing it in wrong way, or there some mistake that they return null from findFragmentByTag... I can't figure out. In case, I've checked some others answers but I can't understand what I really need to do.

viewpager adapter:

public class HomePageAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

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

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                FavoritesFragment favoritesFragment = new FavoritesFragment();
                return favoritesFragment;
            case 1:
                AirTodayFragment airTodayFragment = new AirTodayFragment();
                return airTodayFragment;
            default:
                return null;
        }
    }

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

my xml:

<android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/ad_view_home">

        <android.support.design.widget.AppBarLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:minHeight="?actionBarSize"
            android:theme="@style/ActionBarThemeOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/app_bar"
                android:layout_width="match_parent"
                android:layout_height="?actionBarSize"
                app:layout_scrollFlags="scroll|enterAlways"
                app:logo="@mipmap/ic_launcher_initials"
                app:popupTheme="@style/AppTheme.PopupOverlay"
                app:theme="@style/ActionBarThemeOverlay"
                app:titleTextAppearance="@style/ActionBar.TitleText">
            </android.support.v7.widget.Toolbar>

            <android.support.design.widget.TabLayout
                android:id="@+id/tab_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/app_bar_layout"
                android:background="?attr/colorPrimary"
                android:minHeight="?attr/actionBarSize"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/home_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    </android.support.design.widget.CoordinatorLayout>

EDIT 1: HOW I SOLVED:

public void refreshFavorites(){
    List<Fragment> allFragments = getSupportFragmentManager().getFragments();
    for (Fragment fragmento: allFragments) {
        if (fragmento instanceof FavoritesFragment){
            ((FavoritesFragment) fragmento).executeFavoriteList();
        }
    }
}

EDIT 2: WHERE I USE:

I didn't use refreshFavoretes inside my Activity but actually in Fragments that are inside of it:

@Override
    public void onClick(View v) {
          ...
          // Refresh Favorites
          if (getActivity() instanceof MainActivity) ((MainActivity) getActivity()).refreshFavorites();
    }

You can see more at:

GitHub/MainActivity.Java

and

GitHub/PopularFragment.Java -- Fragment from MainActivity

like image 589
Adley Avatar asked Aug 23 '16 12:08

Adley


People also ask

What is the use of fragment tag?

Fragment tags can be used to avoid recreating a Fragment on Activity orientation change. The Activity is recreated on orientation change, and its onCreate(...) method is called.

How do I attach a fragment to an activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

How do you identify a fragment tag?

findFragmentById(R. id. fragment_container); Alternatively, you can assign a unique tag to a fragment and get a reference using findFragmentByTag() .


1 Answers

You are not setting tag for fragment that is the reason you get null

Instead of using,

FavoritesFragment favoritesFragment = (FavoritesFragment) getSupportFragmentManager()
                       .findFragmentByTag(getString(R.string.fragment_favorite_tag));

use this,

FavoritesFragment favoritesFragment = (FavoritesFragment) getSupportFragmentManager()
                       .getFragments()
                       .get(0);

to get instance of FavoritesFragment.

I have put get(0) as your position of FavoritesFragment instance is at zero. You can get AirTodayFragment instance at position 1 calling get(1)

like image 197
tpk Avatar answered Sep 27 '22 16:09

tpk