AbstractListDetailFragment


public abstract class AbstractListDetailFragment extends Fragment


A fragment supports adaptive two-pane layout. The first child is a list pane, which could be a content list or browser, and the second child is NavHostFragment which controls to navigate between different detail views.

Implementation of the fragment should override this class and implement AbstractListDetailFragment.onCreateListPaneView to supply custom view for the list pane. The fragment provides default NavHostFragment with a NavGraph ID passed in the fragment, and it can be overridden by AbstractListDetailFragment.onCreateDetailPaneNavHostFragment and provide custom NavHostFragment.

Summary

Public constructors

Public methods

final @NonNull NavHostFragment

Return the NavHostFragment this fragment uses

final @NonNull SlidingPaneLayout

Return the SlidingPaneLayout this fragment is currently controlling.

@NonNull NavHostFragment

Return an alternative NavHostFragment to swap the default NavHostFragment in the fragment.

abstract @NonNull View
onCreateListPaneView(
    @NonNull LayoutInflater inflater,
    ViewGroup container,
    Bundle savedInstanceState
)

Provide a list pane view for the fragment.

final @NonNull View
@CallSuper
onCreateView(
    @NonNull LayoutInflater inflater,
    ViewGroup container,
    Bundle savedInstanceState
)

Create the view for the fragment.

void
@CallSuper
onInflate(
    @NonNull Context context,
    @NonNull AttributeSet attrs,
    Bundle savedInstanceState
)

Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity.

void
onListPaneViewCreated(@NonNull View view, Bundle savedInstanceState)

Provides list pane view created in the fragment.

void

Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted.

final void
@CallSuper
onViewCreated(@NonNull View view, Bundle savedInstanceState)

This method provides a callback onListPaneViewCreated after the view hierarchy has been completely created.

void
@CallSuper
onViewStateRestored(Bundle savedInstanceState)

Called when all saved state has been restored into the view hierarchy of the fragment.

Inherited methods

From androidx.fragment.app.Fragment
void
dump(
    @NonNull String prefix,
    @Nullable FileDescriptor fd,
    @NonNull PrintWriter writer,
    @Nullable String[] args
)

Print the Fragments's state into the given stream.

final boolean

Subclasses can not override equals().

final @Nullable FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

boolean

Returns whether the the exit transition and enter transition overlap or not.

boolean

Returns whether the the return transition and reenter transition overlap or not.

final @Nullable Bundle

Return the arguments supplied when the fragment was instantiated, if any.

final @NonNull FragmentManager

Return a private FragmentManager for placing and managing Fragments inside of this Fragment.

@Nullable Context

Return the Context this fragment is currently associated with.

@NonNull CreationExtras

The Fragment's arguments when this is first called will be used as the defaults to any androidx.lifecycle.SavedStateHandle passed to a view model created using this extra.

@NonNull ViewModelProvider.Factory
@Nullable Object

Returns the Transition that will be used to move Views into the initial scene.

@Nullable Object

Returns the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack.

final @Nullable FragmentManager

This method is deprecated.

This has been removed in favor of getParentFragmentManager() which throws an IllegalStateException if the FragmentManager is null.

final @Nullable Object

Return the host object of this fragment.

final int

Return the identifier this fragment is known by.

final @NonNull LayoutInflater

Returns the cached LayoutInflater used to inflate Views of this Fragment.

@NonNull Lifecycle

Overriding this method is no longer supported and this method will be made final in a future version of Fragment.

@NonNull LoaderManager

This method is deprecated.

Use LoaderManager.getInstance(this).

final @Nullable Fragment

Returns the parent Fragment containing this Fragment.

final @NonNull FragmentManager

Return the FragmentManager for interacting with fragments associated with this fragment's activity.

@Nullable Object

Returns the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

final @NonNull Resources

Return requireActivity().getResources().

final boolean

This method is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

@Nullable Object

Returns the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack.

final @NonNull SavedStateRegistry
@Nullable Object

Returns the Transition that will be used for shared elements transferred into the content Scene.

@Nullable Object

Return the Transition that will be used for shared elements transferred back during a pop of the back stack.

final @NonNull String
getString(@StringRes int resId)

Return a localized string from the application's package's default string table.

final @NonNull String
getString(@StringRes int resId, @Nullable Object formatArgs)

Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in java.util.Formatter and format.

final @Nullable String

Get the tag name of the fragment, if specified.

final @Nullable Fragment

This method is deprecated.

Instead of using a target fragment to pass results, use setFragmentResult to deliver results to FragmentResultListener instances registered by other fragments via setFragmentResultListener.

final int

This method is deprecated.

When using the target fragment replacement of setFragmentResultListener and setFragmentResult, consider using setArguments to pass a requestKey if you need to support dynamic request keys.

final @NonNull CharSequence
getText(@StringRes int resId)

Return a localized, styled CharSequence from the application's package's default string table.

boolean

This method is deprecated.

Use setMaxLifecycle instead.

@Nullable View

Get the root view for the fragment's layout (the one returned by onCreateView), if provided.

@NonNull LifecycleOwner

Get a LifecycleOwner that represents the Fragment's View lifecycle.

@NonNull LiveData<@NonNull LifecycleOwner>

Retrieve a LiveData which allows you to observe the lifecycle of the Fragment's View.

@NonNull ViewModelStore

Returns the ViewModelStore associated with this Fragment

final int

Subclasses can not override hashCode().

final boolean

Return true if the fragment is currently added to its activity.

final boolean

Return true if the fragment has been explicitly detached from the UI.

final boolean

Return true if the fragment has been hidden.

final boolean

Return true if the layout is included as part of an activity view hierarchy via the tag.

final boolean

Return true if this fragment is currently being removed from its activity.

final boolean

Return true if the fragment is in the resumed state.

final boolean

Returns true if this fragment is added and its state has already been saved by its host.

final boolean

Return true if the fragment is currently visible to the user.

void

This method is deprecated.

use onViewCreated for code touching the view created by onCreateView and onCreate for other initialization.

void
onActivityResult(int requestCode, int resultCode, @Nullable Intent data)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void

This method is deprecated.

See onAttach.

void

Called when a fragment is first attached to its context.

void

This method is deprecated.

The responsibility for listening for fragments being attached has been moved to FragmentManager.

void
boolean

This hook is called whenever an item in a context menu is selected.

void

Called to do initial creation of a fragment.

@Nullable Animation
@MainThread
onCreateAnimation(int transit, boolean enter, int nextAnim)

Called when a fragment loads an animation.

@Nullable Animator
@MainThread
onCreateAnimator(int transit, boolean enter, int nextAnim)

Called when a fragment loads an animator.

void

Called when a context menu for the view is about to be shown.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void

Called when the fragment is no longer in use.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void

Called when the view previously created by onCreateView has been detached from the fragment.

void

Called when the fragment is no longer attached to its activity.

@NonNull LayoutInflater
onGetLayoutInflater(@Nullable Bundle savedInstanceState)

Returns the LayoutInflater used to inflate Views of this Fragment.

void
@MainThread
onHiddenChanged(boolean hidden)

Called when the hidden state (as returned by isHidden of the fragment or another fragment in its hierarchy has changed.

void
@UiThread
@CallSuper
onInflate(
    @NonNull Activity activity,
    @NonNull AttributeSet attrs,
    @Nullable Bundle savedInstanceState
)

This method is deprecated.

See onInflate.

void
void
onMultiWindowModeChanged(boolean isInMultiWindowMode)

Called when the Fragment's activity changes from fullscreen mode to multi-window mode and visa-versa.

boolean

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void

Called when the Fragment is no longer resumed.

void
onPictureInPictureModeChanged(boolean isInPictureInPictureMode)

Called by the system when the activity changes to and from picture-in-picture mode.

void

This method is deprecated.

androidx.activity.ComponentActivity now implements MenuHost, an interface that allows any component, including your activity itself, to add menu items by calling addMenuProvider without forcing all components through this single method override.

void
@MainThread
onPrimaryNavigationFragmentChanged(
    boolean isPrimaryNavigationFragment
)

Callback for when the primary navigation state of this Fragment has changed.

void
onRequestPermissionsResult(
    int requestCode,
    @NonNull String[] permissions,
    @NonNull int[] grantResults
)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void

Called when the fragment is visible to the user and actively running.

void

Called when the Fragment is visible to the user.

void

Called when the Fragment is no longer started.

void

Postpone the entering Fragment transition until startPostponedEnterTransition or executePendingTransactions has been called.

final void
postponeEnterTransition(long duration, @NonNull TimeUnit timeUnit)

Postpone the entering Fragment transition for a given amount of time and then call startPostponedEnterTransition.

final @NonNull ActivityResultLauncher<@NonNull I>
@MainThread
<I extends Object, O extends Object> registerForActivityResult(
    @NonNull ActivityResultContract<@NonNull I, @NonNull O> contract,
    @NonNull ActivityResultCallback<@NonNull O> callback
)

Register a request to start an activity for result, designated by the given contract.

final @NonNull ActivityResultLauncher<@NonNull I>
@MainThread
<I extends Object, O extends Object> registerForActivityResult(
    @NonNull ActivityResultContract<@NonNull I, @NonNull O> contract,
    @NonNull ActivityResultRegistry registry,
    @NonNull ActivityResultCallback<@NonNull O> callback
)

Register a request to start an activity for result, designated by the given contract.

void

Registers a context menu to be shown for the given view (multiple views can show the context menu).

final void
requestPermissions(@NonNull String[] permissions, int requestCode)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

final @NonNull FragmentActivity

Return the FragmentActivity this fragment is currently associated with.

final @NonNull Bundle

Return the arguments supplied when the fragment was instantiated.

final @NonNull Context

Return the Context this fragment is currently associated with.

final @NonNull FragmentManager

This method is deprecated.

This has been renamed to getParentFragmentManager() to make it clear that you are accessing the FragmentManager that contains this Fragment and not the FragmentManager associated with child Fragments.

final @NonNull Object

Return the host object of this fragment.

final @NonNull Fragment

Returns the parent Fragment containing this Fragment.

final @NonNull View

Get the root view for the fragment's layout (the one returned by onCreateView).

void

Sets whether the the exit transition and enter transition overlap or not.

void

Sets whether the the return transition and reenter transition overlap or not.

void

Supply the construction arguments for this fragment.

void

When custom transitions are used with Fragments, the enter transition callback is called when this Fragment is attached or detached when not popping the back stack.

void

Sets the Transition that will be used to move Views into the initial scene.

void

When custom transitions are used with Fragments, the exit transition callback is called when this Fragment is attached or detached when popping the back stack.

void

Sets the Transition that will be used to move Views out of the scene when the fragment is removed, hidden, or detached when not popping the back stack.

void
setHasOptionsMenu(boolean hasMenu)

This method is deprecated.

This method is no longer needed when using a MenuProvider to provide a Menu to your activity, which replaces onCreateOptionsMenu as the recommended way to provide a consistent, optionally Lifecycle-aware, and modular way to handle menu creation and item selection.

void

Set the initial saved state that this Fragment should restore itself from when first being constructed, as returned by FragmentManager.saveFragmentInstanceState.

void
setMenuVisibility(boolean menuVisible)

Set a hint for whether this fragment's menu should be visible.

void

Sets the Transition that will be used to move Views in to the scene when returning due to popping a back stack.

void
setRetainInstance(boolean retain)

This method is deprecated.

Instead of retaining the Fragment itself, use a non-retained Fragment and keep retained state in a ViewModel attached to that Fragment.

void

Sets the Transition that will be used to move Views out of the scene when the Fragment is preparing to be removed, hidden, or detached because of popping the back stack.

void

Sets the Transition that will be used for shared elements transferred into the content Scene.

void

Sets the Transition that will be used for shared elements transferred back during a pop of the back stack.

void
setTargetFragment(@Nullable Fragment fragment, int requestCode)

This method is deprecated.

Instead of using a target fragment to pass results, the fragment requesting a result should use setFragmentResultListener to register a FragmentResultListener with a requestKey using its parent fragment manager.

void
setUserVisibleHint(boolean isVisibleToUser)

This method is deprecated.

If you are manually calling this method, use setMaxLifecycle instead.

boolean

Gets whether you should show UI with rationale before requesting a permission.

void

Call startActivity from the fragment's containing Activity.

void

Call startActivity from the fragment's containing Activity.

void
startActivityForResult(@NonNull Intent intent, int requestCode)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void
startActivityForResult(
    @NonNull Intent intent,
    int requestCode,
    @Nullable Bundle options
)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void
startIntentSenderForResult(
    @NonNull IntentSender intent,
    int requestCode,
    @Nullable Intent fillInIntent,
    int flagsMask,
    int flagsValues,
    int extraFlags,
    @Nullable Bundle options
)

This method is deprecated.

This method has been deprecated in favor of using the Activity Result API which brings increased type safety via an ActivityResultContract and the prebuilt contracts for common intents available in androidx.activity.result.contract.ActivityResultContracts, provides hooks for testing, and allow receiving results in separate, testable classes independent from your fragment.

void

Begin postponed transitions after postponeEnterTransition was called.

@NonNull String
void

Prevents a context menu to be shown for the given view.

Public constructors

AbstractListDetailFragment

Added in 2.4.0
public AbstractListDetailFragment()

Public methods

getDetailPaneNavHostFragment

Added in 2.4.0
public final @NonNull NavHostFragment getDetailPaneNavHostFragment()

Return the NavHostFragment this fragment uses

Throws
kotlin.IllegalStateException

if the NavHostFragment has not been created by {@link #onCreateView}.

getSlidingPaneLayout

Added in 2.4.0
public final @NonNull SlidingPaneLayout getSlidingPaneLayout()

Return the SlidingPaneLayout this fragment is currently controlling.

Throws
kotlin.IllegalStateException

if the SlidingPaneLayout has not been created by onCreateView

onCreateDetailPaneNavHostFragment

Added in 2.4.0
public @NonNull NavHostFragment onCreateDetailPaneNavHostFragment()

Return an alternative NavHostFragment to swap the default NavHostFragment in the fragment. This method get called when creating the view of the fragment.

onCreateListPaneView

Added in 2.4.0
public abstract @NonNull View onCreateListPaneView(
    @NonNull LayoutInflater inflater,
    ViewGroup container,
    Bundle savedInstanceState
)

Provide a list pane view for the fragment. Called when creating the view of the fragment.

Parameters
@NonNull LayoutInflater inflater

The LayoutInflater that used to inflate the list pane view.

ViewGroup container

The parent view of the list pane view. The parent view can be used to generate the LayoutParams of the view.

Bundle savedInstanceState

The previous saved state of the fragment.

Returns
@NonNull View

Return the list pane view for the fragment.

onCreateView

Added in 2.4.0
@CallSuper
public final @NonNull View onCreateView(
    @NonNull LayoutInflater inflater,
    ViewGroup container,
    Bundle savedInstanceState
)

Create the view for the fragment. This method provides two callbacks to instantiate a list pane view and a NavHostFragment to control navigation between different detail views.

Parameters
@NonNull LayoutInflater inflater

The LayoutInflater that used to inflate the fragment's views.

ViewGroup container

The parent view that the fragment's UI should be attached to.

Bundle savedInstanceState

The previous saved state of the fragment.

Returns
@NonNull View

Return the view for the fragment's UI

onInflate

@CallSuper
public void onInflate(
    @NonNull Context context,
    @NonNull AttributeSet attrs,
    Bundle savedInstanceState
)

Called when a fragment is being created as part of a view layout inflation, typically from setting the content view of an activity. This may be called immediately after the fragment is created from a FragmentContainerView in a layout file. Note this is before the fragment's onAttach has been called; all you should do here is parse the attributes and save them away.

This is called the first time the fragment is inflated. If it is being inflated into a new instance with saved state, this method will not be called a second time for the restored state fragment.

Here is a typical implementation of a fragment that can take parameters both through attributes supplied here as well from getArguments:

public static class MyFragment extends Fragment {
    CharSequence mLabel;

    /**
     * Create a new instance of MyFragment that will be initialized
     * with the given arguments.
     */
    static MyFragment newInstance(CharSequence label) {
        MyFragment f = new MyFragment();
        Bundle b = new Bundle();
        b.putCharSequence("label", label);
        f.setArguments(b);
        return f;
    }

    /**
     * Parse attributes during inflation from a view hierarchy into the
     * arguments we handle.
     */
    @Override
    public void onInflate(@NonNull Context context, @NonNull AttributeSet attrs,
            @Nullable Bundle savedInstanceState) {
        super.onInflate(context, attrs, savedInstanceState);

        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.FragmentArguments);
        mLabel = a.getText(R.styleable.FragmentArguments_android_label);
        a.recycle();
    }

    /**
     * During creation, if arguments have been supplied to the fragment
     * then parse those out.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle args = getArguments();
        if (args != null) {
            CharSequence label = args.getCharSequence("label");
            if (label != null) {
                mLabel = label;
            }
        }
    }

    /**
     * Create the view for this fragment, using the arguments given to it.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.hello_world, container, false);
        View tv = v.findViewById(R.id.text);
        ((TextView)tv).setText(mLabel != null ? mLabel : "(no label)");
        ViewCompat.setBackground(
                tv, ContextCompat.getDrawable(getContext(), android.R.drawable.gallery_thumb));
        return v;
    }
}

Note that parsing the XML attributes uses a "styleable" resource. The declaration for the styleable used here is:

<declare-styleable name="FragmentArguments">
    <attr name="android:label" />
</declare-styleable>

The fragment can then be declared within its activity's content layout through a tag like this:

<androidx.fragment.app.FragmentContainerView
        class="com.example.android.supportv4.app.FragmentArgumentsSupport$MyFragment"
        android:id="@+id/embedded"
        android:layout_width="0px" android:layout_height="wrap_content"
        android:layout_weight="1"
        android:label="@string/fragment_arguments_embedded" />

This fragment can also be created dynamically from arguments given at runtime in the arguments Bundle; here is an example of doing so at creation of the containing activity:

@Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_arguments_support);

    if (savedInstanceState == null) {
        // First-time init; create fragment to embed in activity.
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment newFragment = MyFragment.newInstance("From Arguments");
        ft.add(R.id.created, newFragment);
        ft.commit();
    }
}
Parameters
@NonNull Context context

The Activity that is inflating this fragment.

@NonNull AttributeSet attrs

The attributes at the tag where the fragment is being created.

Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.

onListPaneViewCreated

Added in 2.4.0
public void onListPaneViewCreated(@NonNull View view, Bundle savedInstanceState)

Provides list pane view created in the fragment. Called when the fragment's onViewCreated get called.

Parameters
@NonNull View view

The list pane view created by onCreateListPaneView and added to view hierarchy

Bundle savedInstanceState

The previous saved state of the fragment.

onSaveInstanceState

@CallSuper
public void onSaveInstanceState(@NonNull Bundle outState)

Called to ask the fragment to save its current dynamic state, so it can later be reconstructed in a new instance if its process is restarted. If a new instance of the fragment later needs to be created, the data you place in the Bundle here will be available in the Bundle given to onCreate, onCreateView, and onViewCreated.

This corresponds to Activity.onSaveInstanceState(Bundle) and most of the discussion there applies here as well. Note however: this method may be called at any time before onDestroy. There are many situations where a fragment may be mostly torn down (such as when placed on the back stack with no UI showing), but its state will not be saved until its owning activity actually needs to save its state.

Parameters
@NonNull Bundle outState

Bundle in which to place your saved state.

onViewCreated

Added in 2.4.0
@CallSuper
public final void onViewCreated(@NonNull View view, Bundle savedInstanceState)

This method provides a callback onListPaneViewCreated after the view hierarchy has been completely created.

Parameters
@NonNull View view

The view returned by onCreateView

Bundle savedInstanceState

The previous saved state of the fragment.

onViewStateRestored

@CallSuper
public void onViewStateRestored(Bundle savedInstanceState)

Called when all saved state has been restored into the view hierarchy of the fragment. This can be used to do initialization based on saved state that you are letting the view hierarchy track itself, such as whether check box widgets are currently checked. This is called after onViewCreated and before onStart.

Parameters
Bundle savedInstanceState

If the fragment is being re-created from a previous saved state, this is the state.