Java Code Examples for androidx.fragment.app.Fragment#isAdded()

The following examples show how to use androidx.fragment.app.Fragment#isAdded() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WaypointV2ActionDialog.java    From Android-GSDemo-Gaode-Map with MIT License 6 votes vote down vote up
private void showFragment(Fragment fragment, @IdRes int id) {
    if (fragment == null || fragment.isResumed()) {
        return;
    }

    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    if (fragment.isAdded()) {
        if (fragment instanceof BaseTriggerFragment && currentTriggerFragment != null) {
            transaction.hide(currentTriggerFragment);
        } else if (fragment instanceof IActuatorCallback && currentActuatorFragment != null) {
            transaction.hide(currentActuatorFragment);
        }
        transaction.show(fragment);
    } else {
        transaction.replace(id, fragment);
    }
    transaction.commit();
}
 
Example 2
Source File: FragmentTabAdapter.java    From ZhiHuIndex with Apache License 2.0 6 votes vote down vote up
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
	for (int i = 0; i < rgs.getChildCount(); i++) {
		if (rgs.getChildAt(i).getId() == checkedId) {
			Fragment fragment = fragments.get(i);
			FragmentTransaction ft = obtainFragmentTransaction(i);
			getCurrentFragment().onPause(); 
			if (fragment.isAdded()) {
				fragment.onResume(); 
			} else {
				ft.add(fragmentContentId, fragment);
			}
			showTab(i); 
			ft.commit();

			
			if (null != onRgsExtraCheckedChangedListener) {
				onRgsExtraCheckedChangedListener.OnRgsExtraCheckedChanged(
						radioGroup, checkedId, i);
			}

		}
	}

}
 
Example 3
Source File: SlideAdapter.java    From material-intro with MIT License 6 votes vote down vote up
@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment fragment = getItem(position);
    if (fragment.isAdded()) {
        return fragment;
    }

    Fragment instantiatedFragment = (Fragment) super.instantiateItem(container, position);
    Slide slide = data.get(position);
    if (slide instanceof RestorableSlide) {
        //Load old fragment from fragment manager
        ((RestorableSlide) slide).setFragment(instantiatedFragment);
        data.set(position, slide);
        if (instantiatedFragment instanceof SlideFragment && instantiatedFragment.isAdded()) {
            ((SlideFragment) instantiatedFragment).updateNavigation();
        }
    }
    return instantiatedFragment;
}
 
Example 4
Source File: BaseActivity.java    From NewFastFrame with Apache License 2.0 6 votes vote down vote up
/**
 * 第一次加载的时候调用该方法设置resId
 */
public void addOrReplaceFragment(Fragment fragment, int resId) {
    if (resId != 0) {
        fragmentContainerResId = resId;
    }
    if (fragment == null) {
        return;
    }
    if (currentFragment == null) {
        getSupportFragmentManager().beginTransaction().add(fragmentContainerResId, fragment).show(fragment).commitAllowingStateLoss();
        currentFragment = fragment;
    } else if (currentFragment != fragment) {
        if (fragment.isAdded()) {
            getSupportFragmentManager().beginTransaction().hide(currentFragment).show(fragment).commit();
        } else {
            getSupportFragmentManager().beginTransaction().hide(currentFragment).add(fragmentContainerResId, fragment).show(fragment).commitAllowingStateLoss();
        }
        currentFragment = fragment;
    }
}
 
Example 5
Source File: BaseFragment.java    From NewFastFrame with Apache License 2.0 6 votes vote down vote up
/**
 * 第一次加载的时候调用该方法设置resId
 *
 * @param fragment
 * @param resId
 */
public void addOrReplaceFragment(Fragment fragment, int resId) {
    if (resId != 0) {
        fragmentContainerResId = resId;
    }
    if (fragment == null) {
        return;
    }
    if (currentFragment == null) {
        getChildFragmentManager().beginTransaction().add(resId, fragment).show(fragment).commitAllowingStateLoss();
        currentFragment = fragment;
        return;
    }
    if (fragment.isAdded()) {
        getChildFragmentManager().beginTransaction().hide(currentFragment).show(fragment).commit();
    } else {
        getChildFragmentManager().beginTransaction().hide(currentFragment).add(fragmentContainerResId, fragment).show(fragment).commitAllowingStateLoss();
    }
    currentFragment = fragment;
}
 
Example 6
Source File: MainActivity.java    From animation-samples with Apache License 2.0 6 votes vote down vote up
@Override
public void onBackPressed() {
    /** @see BackPressAware */
    for (Fragment fragment : mFragmentManager.getFragments()) {
        if (fragment instanceof BackPressAware && fragment.isAdded()) {
            // Enable a single fragment to intercept the back press.
            ((BackPressAware) fragment).onBackPressed();
            return;
        }
    }
    // Intercept all back press calls until there's no more fragments on the back stack.
    mFragmentManager.popBackStack();
    if (mFragmentManager.getBackStackEntryCount() == 0) {
        super.onBackPressed();
    }
}
 
Example 7
Source File: MainActivity.java    From QuickDevFramework with Apache License 2.0 6 votes vote down vote up
private void switchFragment(String tag) {
    /* Fragment 切换 */
    FragmentTransaction transaction = mFragmentManager.beginTransaction();
    if (fragmentTags.indexOf(tag) < 0) {
        return;
    }
    Fragment showFragment = fragments.get(fragmentTags.indexOf(tag));
    Fragment currentFragment = mFragmentManager.findFragmentByTag(currentTag);
    if (currentFragment != null) {
        transaction.hide(currentFragment);
    }
    if (showFragment.isAdded()) {
        transaction.show(showFragment);
    }
    else {
        transaction.add(R.id.content_frame, showFragment, tag);
        transaction.show(showFragment);
    }
    transaction.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    transaction.commitAllowingStateLoss();
    currentTag = tag;
}
 
Example 8
Source File: MainActivity.java    From DKVideoPlayer with Apache License 2.0 5 votes vote down vote up
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
    int index;
    int itemId = menuItem.getItemId();
    switch (itemId) {
        default:
        case R.id.tab_api:
            index = 0;
            break;
        case R.id.tab_list:
            index = 1;
            break;
        case R.id.tab_extension:
            index = 2;
            break;
        case R.id.tab_pip:
            index = 3;
            break;
    }

    if (mCurrentIndex != index) {
        //切换tab,释放正在播放的播放器
        if (mCurrentIndex == 1) {
            getVideoViewManager().releaseByTag(Tag.LIST);
            getVideoViewManager().releaseByTag(Tag.SEAMLESS, false);//注意不能移除
        }
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment fragment = mFragments.get(index);
        Fragment curFragment = mFragments.get(mCurrentIndex);
        if (fragment.isAdded()) {
            transaction.hide(curFragment).show(fragment);
        } else {
            transaction.add(R.id.layout_content, fragment).hide(curFragment);
        }
        transaction.commitAllowingStateLoss();
        mCurrentIndex = index;
    }
    return true;
}
 
Example 9
Source File: LibraryFragment.java    From VinylMusicPlayer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    if (pager == null) return;
    inflater.inflate(R.menu.menu_main, menu);
    if (isPlaylistPage()) {
        menu.add(0, R.id.action_new_playlist, 0, R.string.new_playlist_title);
    }
    Fragment currentFragment = getCurrentFragment();
    if (currentFragment instanceof AbsLibraryPagerRecyclerViewCustomGridSizeFragment && currentFragment.isAdded()) {
        AbsLibraryPagerRecyclerViewCustomGridSizeFragment absLibraryRecyclerViewCustomGridSizeFragment = (AbsLibraryPagerRecyclerViewCustomGridSizeFragment) currentFragment;

        MenuItem gridSizeItem = menu.findItem(R.id.action_grid_size);
        if (Util.isLandscape(getResources())) {
            gridSizeItem.setTitle(R.string.action_grid_size_land);
        }
        setUpGridSizeMenu(absLibraryRecyclerViewCustomGridSizeFragment, gridSizeItem.getSubMenu());

        menu.findItem(R.id.action_colored_footers).setChecked(absLibraryRecyclerViewCustomGridSizeFragment.usePalette());
        menu.findItem(R.id.action_colored_footers).setEnabled(absLibraryRecyclerViewCustomGridSizeFragment.canUsePalette());

        setUpSortOrderMenu(absLibraryRecyclerViewCustomGridSizeFragment, menu.findItem(R.id.action_sort_order).getSubMenu());
    } else {
        menu.removeItem(R.id.action_grid_size);
        menu.removeItem(R.id.action_colored_footers);
        menu.removeItem(R.id.action_sort_order);
    }
    Activity activity = getActivity();
    if (activity == null) return;
    ToolbarContentTintHelper.handleOnCreateOptionsMenu(getActivity(), toolbar, menu, ATHToolbarActivity.getToolbarBackgroundColor(toolbar));
}
 
Example 10
Source File: FragmentChangeManager.java    From UIWidget with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化fragments
 */
private void initFragments() {
    for (Fragment fragment : mFragments) {
        if (fragment.isAdded()) {
            mFragmentManager.beginTransaction().hide(fragment).commit();
        } else {
            mFragmentManager.beginTransaction().add(mContainerViewId, fragment).hide(fragment).commit();
        }
    }
    setFragments(0);
}
 
Example 11
Source File: FragmentLifecycleActivity.java    From AndroidAll with Apache License 2.0 5 votes vote down vote up
public void showFragment(@NonNull Fragment fragment) {
    //相当于new一个实例FragmentTransaction
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    if (fragment.isAdded()) {
        ft.show(fragment);
    } else {
        //把该ft加入到栈中进行管理
        ft.addToBackStack(fragment.getClass().getSimpleName());
        ft.add(R.id.container, fragment);
    }
    ft.commitAllowingStateLoss();
    Log.e("Lifecycle", "getBackStackEntryCount: " + getSupportFragmentManager().getBackStackEntryCount());
}
 
Example 12
Source File: UiUtil.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
/**
 * Method to remove the child {@link Fragment} against the provided tag.
 *
 * @param parentFragment {@link Fragment} that containing the child {@link Fragment}
 * @param tag            string to search the fragment.
 */
public static void removeFragmentByTag(@NonNull Fragment parentFragment, @NonNull String tag) {
    if (parentFragment.isAdded()) {
        final FragmentManager fragmentManager = parentFragment.getChildFragmentManager();
        final Fragment fragment = fragmentManager.findFragmentByTag(tag);
        if (fragment != null) {
            fragmentManager.beginTransaction().remove(fragment)
                    .commitAllowingStateLoss();
        }
    }
}
 
Example 13
Source File: FragmentStack.java    From cathode with Apache License 2.0 5 votes vote down vote up
private void removeFragment(Fragment fragment) {
  if (fragment != null && (fragment.isAdded() || fragment.isDetached())) {
    Timber.d("Removing fragment: %s", fragment.getTag());

    ensureTransaction();
    fragmentTransaction.remove(fragment);
  }
}
 
Example 14
Source File: FragmentHelper.java    From AndroidNavigation with MIT License 5 votes vote down vote up
@NonNull
public static List<AwesomeFragment> getFragmentsAtAddedList(@NonNull FragmentManager fragmentManager) {
    List<AwesomeFragment> children = new ArrayList<>();
    List<Fragment> fragments = fragmentManager.getFragments();
    for (int i = 0, size = fragments.size(); i < size; i++) {
        Fragment fragment = fragments.get(i);
        if (fragment instanceof AwesomeFragment && fragment.isAdded()) {
            children.add((AwesomeFragment) fragment);
        }
    }
    return children;
}
 
Example 15
Source File: SettingsActivity.java    From MaxLock with GNU General Public License v3.0 5 votes vote down vote up
public static void showMultipaneIfInLandscape(SettingsActivity activity) {
    if (activity.secondFragmentContainer != null) {
        activity.secondFragmentContainer.setVisibility(View.VISIBLE);
        FragmentManager manager = activity.getSupportFragmentManager();
        Fragment secondPane = manager.findFragmentByTag(TAG_PREFERENCE_FRAGMENT_SECOND_PANE);
        if (secondPane == null) {
            secondPane = MaxLockPreferenceFragment.Screen.MAIN.getScreen();
        }
        if (!secondPane.isAdded())
            manager.beginTransaction().replace(R.id.second_fragment_container, secondPane, TAG_PREFERENCE_FRAGMENT_SECOND_PANE).commit();
    }
}
 
Example 16
Source File: AwesomeFragment.java    From AndroidNavigation with MIT License 5 votes vote down vote up
@Override
protected void dismissInternal(boolean allowStateLoss, boolean fromOnDismiss) {
    super.dismissInternal(allowStateLoss, fromOnDismiss);
    Fragment target = getTargetFragment();
    if (target instanceof AwesomeFragment && target.isAdded() && fromOnDismiss) {
        FragmentHelper.executePendingTransactionsSafe(requireFragmentManager());
        AwesomeFragment fragment = (AwesomeFragment) target;
        fragment.onFragmentResult(getRequestCode(), getResultCode(), getResultData());
    }
}
 
Example 17
Source File: AwesomeActivity.java    From AndroidNavigation with MIT License 5 votes vote down vote up
protected void showDialogInternal(AwesomeFragment dialog, int requestCode) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    if (fragmentManager.getBackStackEntryCount() > 0) {
        Fragment fragment = fragmentManager.findFragmentById(android.R.id.content);
        if (fragment != null && fragment.isAdded()) {
            dialog.setTargetFragment(fragment, requestCode);
        }
    }
    Bundle args = FragmentHelper.getArguments(dialog);
    args.putBoolean(AwesomeFragment.ARGS_SHOW_AS_DIALOG, true);
    dialog.show(fragmentManager, dialog.getSceneId());
    FragmentHelper.executePendingTransactionsSafe(fragmentManager);
}
 
Example 18
Source File: TaskHelper.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
static boolean isFragmentDestroyed(Fragment fragment) {
  return fragment.isRemoving()
      || fragment.getActivity() == null
      || fragment.isDetached()
      || !fragment.isAdded()
      || fragment.getView() == null;
}
 
Example 19
Source File: MessageActivity.java    From tindroid with Apache License 2.0 4 votes vote down vote up
void showFragment(String tag, Bundle args, boolean addToBackstack) {
    if (isFinishing() || isDestroyed()) {
        return;
    }

    FragmentManager fm = getSupportFragmentManager();

    Fragment fragment = fm.findFragmentByTag(tag);
    if (fragment == null) {
        switch (tag) {
            case FRAGMENT_MESSAGES:
                fragment = new MessagesFragment();
                break;
            case FRAGMENT_INFO:
                fragment = new TopicInfoFragment();
                break;
            case FRAGMENT_PERMISSIONS:
                fragment = new TopicPermissionsFragment();
                break;
            case FRAGMENT_EDIT_MEMBERS:
                fragment = new EditMembersFragment();
                break;
            case FRAGMENT_VIEW_IMAGE:
                fragment = new ImageViewFragment();
                break;
            case FRAGMENT_FILE_PREVIEW:
                fragment = new FilePreviewFragment();
                break;
            case FRAGMENT_INVALID:
                fragment = new InvalidTopicFragment();
                break;
        }
    } else if (args == null) {
        // Retain old arguments.
        args = fragment.getArguments();
    }
    if (fragment == null) {
        throw new NullPointerException();
    }

    args = args != null ? args : new Bundle();
    args.putString("topic", mTopicName);
    args.putString(MessagesFragment.MESSAGE_TO_SEND, mMessageText);
    if (fragment.getArguments() != null) {
        fragment.getArguments().putAll(args);
    } else {
        fragment.setArguments(args);
    }

    FragmentTransaction trx = fm.beginTransaction();
    if (!fragment.isAdded()) {
        trx = trx.replace(R.id.contentFragment, fragment, tag)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
    } else if (!fragment.isVisible()) {
        trx = trx.show(fragment);
    } else {
        addToBackstack = false;
    }

    if (FRAGMENT_MESSAGES.equals(tag)) {
        trx.setPrimaryNavigationFragment(fragment);
    }

    if (addToBackstack) {
        trx.addToBackStack(tag);
    }
    if (!trx.isEmpty()) {
        trx.commit();
    }
}
 
Example 20
Source File: UiUtils.java    From tindroid with Apache License 2.0 4 votes vote down vote up
/**
 * Decodes and scales a contact's image from a file pointed to by a Uri in the contact's data,
 * and returns the result as a Bitmap. The column that contains the Uri varies according to the
 * platform version.
 *
 * @param photoData For platforms prior to Android 3.0, provide the Contact._ID column value.
 *                  For Android 3.0 and later, provide the Contact.PHOTO_THUMBNAIL_URI value.
 * @param imageSize The desired target width and height of the output image in pixels.
 * @return A Bitmap containing the contact's image, resized to fit the provided image size. If
 * no thumbnail exists, returns null.
 */
private static Bitmap loadContactPhotoThumbnail(Fragment fragment, String photoData, int imageSize) {

    // Ensures the Fragment is still added to an activity. As this method is called in a
    // background thread, there's the possibility the Fragment is no longer attached and
    // added to an activity. If so, no need to spend resources loading the contact photo.
    if (!fragment.isAdded()) {
        return null;
    }

    Activity activity = fragment.getActivity();
    if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
        return null;
    }

    // Instantiates an AssetFileDescriptor. Given a content Uri pointing to an image file, the
    // ContentResolver can return an AssetFileDescriptor for the file.

    // This "try" block catches an Exception if the file descriptor returned from the Contacts
    // Provider doesn't point to an existing file.
    Uri thumbUri = Uri.parse(photoData);
    try (AssetFileDescriptor afd = activity.getContentResolver().openAssetFileDescriptor(thumbUri, "r")) {

        // Retrieves a file descriptor from the Contacts Provider. To learn more about this
        // feature, read the reference documentation for
        // ContentResolver#openAssetFileDescriptor.

        // Gets a FileDescriptor from the AssetFileDescriptor. A BitmapFactory object can
        // decode the contents of a file pointed to by a FileDescriptor into a Bitmap.
        if (afd != null) {
            // Decodes a Bitmap from the image pointed to by the FileDescriptor, and scales it
            // to the specified width and height
            return ImageLoader.decodeSampledBitmapFromStream(
                    new BufferedInputStream(new FileInputStream(afd.getFileDescriptor())), imageSize, imageSize);
        }
    } catch (IOException e) {
        // If the file pointed to by the thumbnail URI doesn't exist, or the file can't be
        // opened in "read" mode, ContentResolver.openAssetFileDescriptor throws a
        // FileNotFoundException.
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData
                    + ": " + e.toString());
        }
    }
    // If an AssetFileDescriptor was returned, try to close it
    // Closing a file descriptor might cause an IOException if the file is
    // already closed. Nothing extra is needed to handle this.

    // If the decoding failed, returns null
    return null;
}