How to know if any fragment is active or visible?

Solution 1:

If you want to change title of toolbar in activity for different fragments than use interface.

Create interface :

public interface OnFragmentTitleChangeListener {
    void onFragmentTitle(String strTitle);
}

Implement this interface in your activity

public class YourActivity extends AppCompatActivity implements OnFragmentTitleChangeListener
{
  TextView title;
  ......
  ......
  // Initialize title in onCreate method
  ......
  ......
  // Override this method
  public void onFragmentTitle(String strTitle) 
  {
      title.setText(strTitle);
  }

  @Override
  public void onBackPressed() {
    FragmentManager fm = getSupportFragmentManager();

    if (onBack(fm)) {
        return;
    }
    super.onBackPressed();
  }

  private boolean onBack(FragmentManager fm) {
     if (fm != null) {
        if (fm.getBackStackEntryCount() > 0) {
            fm.popBackStack();
            return true;
        }
    }
    return false;
  }
}

After that set text from fragment's onResume method.

@Override
public void onResume() {
    super.onResume();
    ((OnFragmentTitleChangeListener) mContext).onFragmentTitle(getResources().getString(R.string.yourtext));
}

Solution 2:

This function let you know if the fragment is visible or not

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // Handle when fragment is visible
    } else {
        // And not
    }
}

But in your use-case, if you using ViewPager or Tab, you can get your title easily by this

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            yourFragmentPagerAdapter.getTitle(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });