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

The following examples show how to use androidx.fragment.app.Fragment#getActivity() . 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: Fragments.java    From particle-android with Apache License 2.0 6 votes vote down vote up
/**
 * Return the callbacks for a fragment or throw an exception.
 * <p/>
 * Inspired by: https://gist.github.com/keyboardr/5455206
 */
@SuppressWarnings("unchecked")
public static <T> T getCallbacksOrThrow(Fragment frag, Class<T> callbacks) {
    Fragment parent = frag.getParentFragment();

    if (parent != null && callbacks.isInstance(parent)) {
        return (T) parent;

    } else {
        FragmentActivity activity = frag.getActivity();
        if (activity != null && callbacks.isInstance(activity)) {
            return (T) activity;
        }
    }

    // We haven't actually failed a class cast thanks to the checks above, but that's the
    // idiomatic approach for this pattern with fragments.
    throw new ClassCastException("This fragment's activity or parent fragment must implement "
            + callbacks.getCanonicalName());
}
 
Example 2
Source File: UiUtils.java    From tindroid with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
static void requestAvatar(@Nullable Fragment fragment) {
    if (fragment == null) {
        return;
    }

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

    if (!isPermissionGranted(activity, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
        fragment.requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                READ_EXTERNAL_STORAGE_PERMISSION);
    } else {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);

        fragment.startActivityForResult(Intent.createChooser(intent, fragment.getString(R.string.select_image)),
                ACTIVITY_RESULT_SELECT_PICTURE);
    }
}
 
Example 3
Source File: PuzzleActivity.java    From EasyPhotos with Apache License 2.0 6 votes vote down vote up
public static void startWithPhotos(Fragment fragment, ArrayList<Photo> photos, int requestCode, boolean replaceCustom, @NonNull ImageEngine imageEngine) {
    if (null != toClass) {
        toClass.clear();
        toClass = null;
    }
    if (Setting.imageEngine != imageEngine) {
        Setting.imageEngine = imageEngine;
    }
    Intent intent = new Intent(fragment.getActivity(), PuzzleActivity.class);
    intent.putExtra(Key.PUZZLE_FILE_IS_PHOTO, true);
    intent.putParcelableArrayListExtra(Key.PUZZLE_FILES, photos);
    if (replaceCustom) {
        if (fragment.getActivity() != null) {
            toClass = new WeakReference<Class<? extends Activity>>(fragment.getActivity().getClass());
        }
    }
    fragment.startActivityForResult(intent, requestCode);
}
 
Example 4
Source File: UiUtils.java    From tindroid with Apache License 2.0 6 votes vote down vote up
static ImageLoader getImageLoaderInstance(final Fragment parent) {
    FragmentActivity activity = parent.getActivity();
    if (activity == null) {
        return null;
    }

    ImageLoader il = new ImageLoader(getListPreferredItemHeight(parent),
            activity.getSupportFragmentManager()) {
        @Override
        protected Bitmap processBitmap(Object data) {
            // This gets called in a background thread and passed the data from
            // ImageLoader.loadImage().
            return UiUtils.loadContactPhotoThumbnail(parent,
                    (String) data, getImageSize());
        }
    };
    // Set a placeholder loading image for the image loader
    il.setLoadingImage(activity, R.drawable.ic_person_circle);

    return il;
}
 
Example 5
Source File: IntentUtils.java    From PixivforMuzei3 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Launch {@link Activity} safely with {@link Fragment}
 *
 * @param requestCode req-code for {@link Activity#startActivityForResult(Intent, int)}, or -1
 * @param title       intent chooser title if needed
 * @param options     options for start activity
 * @return true if start succeed, else false
 */
public static boolean launchActivity(@NonNull Fragment fragment, @Nullable Intent intent, int requestCode,
                                     @Nullable CharSequence title, @Nullable Bundle options) {
    Objects.requireNonNull(fragment);

    Activity activity = fragment.getActivity();
    if (intent == null || activity == null) {
        return false;
    }
    if (activity.getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) == null) {
        return false;
    }

    Intent pending = TextUtils.isEmpty(title) ? intent : Intent.createChooser(intent, title);

    if (requestCode != -1) {
        fragment.startActivityForResult(pending, requestCode, options);
    } else {
        fragment.startActivity(pending, options);
    }
    return true;
}
 
Example 6
Source File: Utils.java    From SAI with GNU General Public License v3.0 5 votes vote down vote up
public static void hideKeyboard(Fragment fragment) {
    Activity activity = fragment.getActivity();
    if (activity != null) {
        hideKeyboard(activity);
        return;
    }

    InputMethodManager inputMethodManager = (InputMethodManager) fragment.requireContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(fragment.requireView().getWindowToken(), 0);
}
 
Example 7
Source File: Utils.java    From SAI with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
public static <T> T getParentAs(Fragment fragment, Class<T> asClass) {
    Object parent = fragment.getParentFragment();
    if (parent == null)
        parent = fragment.getActivity();

    if (asClass.isInstance(parent))
        return asClass.cast(parent);

    return null;
}
 
Example 8
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 9
Source File: BrowserSwitchClient.java    From browser-switch-android with MIT License 5 votes vote down vote up
/**
 * Open a browser or <a href="https://developer.chrome.com/multidevice/android/customtabs">Chrome Custom Tab</a>
 * with the given intent from an Android fragment. The fragment must be attached to activity when invoking this method.
 *
 * @param requestCode the request code used to differentiate requests from one another.
 * @param intent the intent to use to initiate a browser switch
 * @param fragment the fragment used to start browser switch
 * @param listener the listener that will receive browser switch callbacks
 */
public void start(
    int requestCode, Intent intent, Fragment fragment, BrowserSwitchListener listener) {
    FragmentActivity activity = fragment.getActivity();
    if (activity != null) {
        start(requestCode, intent, activity, listener);
    } else {
        throw new IllegalStateException("Fragment must be attached to an activity.");
    }
}
 
Example 10
Source File: ViewModelProviders.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static Activity checkActivity(Fragment fragment) {
    Activity activity = fragment.getActivity();
    if (activity == null) {
        throw new IllegalStateException("Can't create ViewModelProvider for detached fragment");
    }
    return activity;
}
 
Example 11
Source File: GlideHelper.java    From hipda with GNU General Public License v2.0 4 votes vote down vote up
public static boolean isOkToLoad(Fragment fragment) {
    return fragment != null && fragment.getActivity() != null && !fragment.isDetached();
}
 
Example 12
Source File: CardTriggerPresenter.java    From science-journal with Apache License 2.0 4 votes vote down vote up
public CardTriggerPresenter(OnCardTriggerClickedListener listener, Fragment fragment) {
  this.listener = listener;
  // In tests, the fragment may be null.
  activity = fragment != null ? fragment.getActivity() : null;
}
 
Example 13
Source File: PictureSelector.java    From PictureSelector with Apache License 2.0 4 votes vote down vote up
private PictureSelector(Fragment fragment, int requestCode) {
    this(fragment.getActivity(), fragment, requestCode);
}
 
Example 14
Source File: PermissionHelper.java    From openScale with GNU General Public License v3.0 4 votes vote down vote up
public static boolean requestBluetoothPermission(final Fragment fragment) {
    final BluetoothManager bluetoothManager = (BluetoothManager) fragment.getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
    BluetoothAdapter btAdapter = bluetoothManager.getAdapter();

    if (btAdapter == null || !btAdapter.isEnabled()) {
        Toast.makeText(fragment.getContext(), "Bluetooth " + fragment.getContext().getResources().getString(R.string.info_is_not_enable), Toast.LENGTH_SHORT).show();

        if (btAdapter != null) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            fragment.getActivity().startActivityForResult(enableBtIntent, ENABLE_BLUETOOTH_REQUEST);
        }
        return false;
    }

    // Check if Bluetooth 4.x is available
    if (!fragment.getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
        Toast.makeText(fragment.getContext(), "Bluetooth 4.x " + fragment.getContext().getResources().getString(R.string.info_is_not_available), Toast.LENGTH_SHORT).show();
        return false;
     }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (fragment.getContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            AlertDialog.Builder builder = new AlertDialog.Builder(fragment.getActivity());

            builder.setMessage(R.string.permission_bluetooth_info)
                    .setTitle(R.string.permission_bluetooth_info_title)
                    .setIcon(R.drawable.ic_preferences_about)
                    .setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                            fragment.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
                        }
                    });

            Dialog alertDialog = builder.create();
            alertDialog.setCanceledOnTouchOutside(false);
            alertDialog.show();
            return false;
        }
    }

    return true;
}
 
Example 15
Source File: PictureSelector.java    From PictureSelector with Apache License 2.0 4 votes vote down vote up
private PictureSelector(Fragment fragment) {
    this(fragment.getActivity(), fragment);
}
 
Example 16
Source File: Matisse.java    From Matisse with Apache License 2.0 4 votes vote down vote up
private Matisse(Fragment fragment) {
    this(fragment.getActivity(), fragment);
}
 
Example 17
Source File: ImmersionBar.java    From MyBookshelf with GNU General Public License v3.0 2 votes vote down vote up
/**
 * 在Fragment里初始化
 * Instantiates a new Immersion bar.
 *
 * @param fragment the fragment
 */
private ImmersionBar(Fragment fragment) {
    this(fragment.getActivity(), fragment);
}
 
Example 18
Source File: ImmersionBar.java    From a with GNU General Public License v3.0 2 votes vote down vote up
/**
 * 在Fragment里初始化
 * Instantiates a new Immersion bar.
 *
 * @param fragment the fragment
 */
private ImmersionBar(Fragment fragment) {
    this(fragment.getActivity(), fragment);
}
 
Example 19
Source File: ClipImageActivity.java    From ImageSelector with Apache License 2.0 2 votes vote down vote up
/**
 * 启动图片选择器
 *
 * @param fragment
 * @param requestCode
 * @param config
 */
public static void openActivity(Fragment fragment, int requestCode, RequestConfig config) {
    Intent intent = new Intent(fragment.getActivity(), ClipImageActivity.class);
    intent.putExtra(ImageSelector.KEY_CONFIG, config);
    fragment.startActivityForResult(intent, requestCode);
}
 
Example 20
Source File: ImageSelectorActivity.java    From ImageSelector with Apache License 2.0 2 votes vote down vote up
/**
 * 启动图片选择器
 *
 * @param fragment
 * @param requestCode
 * @param config
 */
public static void openActivity(Fragment fragment, int requestCode, RequestConfig config) {
    Intent intent = new Intent(fragment.getActivity(), ImageSelectorActivity.class);
    intent.putExtra(ImageSelector.KEY_CONFIG, config);
    fragment.startActivityForResult(intent, requestCode);
}