public class

LeanbackEditTextPreferenceDialogFragmentCompat

extends LeanbackPreferenceDialogFragmentCompat

 java.lang.Object

androidx.fragment.app.Fragment

androidx.leanback.preference.LeanbackPreferenceDialogFragmentCompat

↳androidx.leanback.preference.LeanbackEditTextPreferenceDialogFragmentCompat

Gradle dependencies

compile group: 'androidx.leanback', name: 'leanback-preference', version: '1.2.0-alpha04'

  • groupId: androidx.leanback
  • artifactId: leanback-preference
  • version: 1.2.0-alpha04

Artifact androidx.leanback:leanback-preference:1.2.0-alpha04 it located at Google repository (https://maven.google.com/)

Androidx artifact mapping:

androidx.leanback:leanback-preference com.android.support:preference-leanback-v17

Overview

Implemented a dialog to input text.

Summary

Fields
public static final java.lang.StringEXTRA_IME_OPTIONS

public static final java.lang.StringEXTRA_INPUT_TYPE

from LeanbackPreferenceDialogFragmentCompatARG_KEY
from FragmentmPreviousWho
Constructors
publicLeanbackEditTextPreferenceDialogFragmentCompat()

Methods
public static LeanbackEditTextPreferenceDialogFragmentCompatnewInstance(java.lang.String key)

Create a new LeanbackListPreferenceDialogFragmentCompat.

public voidonCreate(Bundle savedInstanceState)

Called to do initial creation of a fragment.

public ViewonCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

Called to have the fragment instantiate its user interface view.

public voidonSaveInstanceState(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.

public voidonStart()

Called when the Fragment is visible to the user.

from LeanbackPreferenceDialogFragmentCompatgetPreference
from Fragmentdump, equals, getActivity, getAllowEnterTransitionOverlap, getAllowReturnTransitionOverlap, getArguments, getChildFragmentManager, getContext, getDefaultViewModelCreationExtras, getDefaultViewModelProviderFactory, getEnterTransition, getExitTransition, getFragmentManager, getHost, getId, getLayoutInflater, getLayoutInflater, getLifecycle, getLoaderManager, getParentFragment, getParentFragmentManager, getReenterTransition, getResources, getRetainInstance, getReturnTransition, getSavedStateRegistry, getSharedElementEnterTransition, getSharedElementReturnTransition, getString, getString, getTag, getTargetFragment, getTargetRequestCode, getText, getUserVisibleHint, getView, getViewLifecycleOwner, getViewLifecycleOwnerLiveData, getViewModelStore, hashCode, hasOptionsMenu, instantiate, instantiate, isAdded, isDetached, isHidden, isInLayout, isMenuVisible, isRemoving, isResumed, isStateSaved, isVisible, onActivityCreated, onActivityResult, onAttach, onAttach, onAttachFragment, onConfigurationChanged, onContextItemSelected, onCreateAnimation, onCreateAnimator, onCreateContextMenu, onCreateOptionsMenu, onDestroy, onDestroyOptionsMenu, onDestroyView, onDetach, onGetLayoutInflater, onHiddenChanged, onInflate, onInflate, onLowMemory, onMultiWindowModeChanged, onOptionsItemSelected, onOptionsMenuClosed, onPause, onPictureInPictureModeChanged, onPrepareOptionsMenu, onPrimaryNavigationFragmentChanged, onRequestPermissionsResult, onResume, onStop, onViewCreated, onViewStateRestored, postponeEnterTransition, postponeEnterTransition, registerForActivityResult, registerForActivityResult, registerForContextMenu, requestPermissions, requireActivity, requireArguments, requireContext, requireFragmentManager, requireHost, requireParentFragment, requireView, setAllowEnterTransitionOverlap, setAllowReturnTransitionOverlap, setArguments, setEnterSharedElementCallback, setEnterTransition, setExitSharedElementCallback, setExitTransition, setHasOptionsMenu, setInitialSavedState, setMenuVisibility, setReenterTransition, setRetainInstance, setReturnTransition, setSharedElementEnterTransition, setSharedElementReturnTransition, setTargetFragment, setUserVisibleHint, shouldShowRequestPermissionRationale, startActivity, startActivity, startActivityForResult, startActivityForResult, startIntentSenderForResult, startPostponedEnterTransition, toString, unregisterForContextMenu
from java.lang.Objectclone, finalize, getClass, notify, notifyAll, wait, wait, wait

Fields

public static final java.lang.String EXTRA_INPUT_TYPE

public static final java.lang.String EXTRA_IME_OPTIONS

Constructors

public LeanbackEditTextPreferenceDialogFragmentCompat()

Methods

public static LeanbackEditTextPreferenceDialogFragmentCompat newInstance(java.lang.String key)

Create a new LeanbackListPreferenceDialogFragmentCompat.

Parameters:

key: The key of EditTextPreference it will be created from.

Returns:

A new LeanbackEditTextPreferenceDialogFragmentCompat to display.

public void onCreate(Bundle savedInstanceState)

Called to do initial creation of a fragment. This is called after Fragment.onAttach(Activity) and before Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle).

Note that this can be called while the fragment's activity is still in the process of being created. As such, you can not rely on things like the activity's content view hierarchy being initialized at this point. If you want to do work once the activity itself is created, add a LifecycleObserver on the activity's Lifecycle, removing it when it receives the callback.

Any restored child fragments will be created before the base Fragment.onCreate method returns.

Parameters:

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

public void onSaveInstanceState(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 Fragment.onCreate(Bundle), Fragment.onCreateView(LayoutInflater, ViewGroup, Bundle), and Fragment.onViewCreated(View, Bundle).

This corresponds to and most of the discussion there applies here as well. Note however: this method may be called at any time before Fragment.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:

outState: Bundle in which to place your saved state.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)

Called to have the fragment instantiate its user interface view. This is optional, and non-graphical fragments can return null. This will be called between Fragment.onCreate(Bundle) and Fragment.onViewCreated(View, Bundle).

A default View can be returned by calling Fragment.Fragment(int) in your constructor. Otherwise, this method returns null.

It is recommended to only inflate the layout in this method and move logic that operates on the returned View to Fragment.onViewCreated(View, Bundle).

If you return a View from here, you will later be called in Fragment.onDestroyView() when the view is being released.

Parameters:

inflater: The LayoutInflater object that can be used to inflate any views in the fragment,
container: If non-null, this is the parent view that the fragment's UI should be attached to. The fragment should not add the view itself, but this can be used to generate the LayoutParams of the view.
savedInstanceState: If non-null, this fragment is being re-constructed from a previous saved state as given here.

Returns:

Return the View for the fragment's UI, or null.

public void onStart()

Called when the Fragment is visible to the user. This is generally tied to of the containing Activity's lifecycle.

Source

/*
 * Copyright 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.leanback.preference;

import android.content.Context;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.preference.DialogPreference;
import androidx.preference.EditTextPreference;

/**
 * Implemented a dialog to input text.
 */
public class LeanbackEditTextPreferenceDialogFragmentCompat extends
        LeanbackPreferenceDialogFragmentCompat {

    public static final String EXTRA_INPUT_TYPE = "input_type";
    public static final String EXTRA_IME_OPTIONS = "ime_option";

    private static final int DEFAULT_INPUT_TYPE = InputType.TYPE_CLASS_TEXT;
    private static final int DEFAULT_IME_OPTIONS = EditorInfo.IME_ACTION_GO;

    private static final String SAVE_STATE_TITLE = "LeanbackEditPreferenceDialog.title";
    private static final String SAVE_STATE_MESSAGE = "LeanbackEditPreferenceDialog.message";
    private static final String SAVE_STATE_TEXT = "LeanbackEditPreferenceDialog.text";
    private static final String SAVE_STATE_INPUT_TYPE = "LeanbackEditPreferenceDialog.inputType";
    private static final String SAVE_STATE_IME_OPTIONS = "LeanbackEditPreferenceDialog.imeOptions";

    private CharSequence mDialogTitle;
    private CharSequence mDialogMessage;
    private CharSequence mText;
    private int mImeOptions;
    private int mInputType;

    /**
     * Create a new LeanbackListPreferenceDialogFragmentCompat.
     * @param key The key of {@link EditTextPreference} it will be created from.
     * @return A new LeanbackEditTextPreferenceDialogFragmentCompat to display.
     */
    public static LeanbackEditTextPreferenceDialogFragmentCompat newInstance(String key) {
        final Bundle args = new Bundle(1);
        args.putString(ARG_KEY, key);

        final LeanbackEditTextPreferenceDialogFragmentCompat
                fragment = new LeanbackEditTextPreferenceDialogFragmentCompat();
        fragment.setArguments(args);

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState == null) {
            final DialogPreference preference = getPreference();
            mDialogTitle = preference.getDialogTitle();
            mDialogMessage = preference.getDialogMessage();
            if (preference instanceof EditTextPreference) {
                mDialogTitle = preference.getDialogTitle();
                mDialogMessage = preference.getDialogMessage();
                mText = ((EditTextPreference) preference).getText();
                mInputType = preference.getExtras().getInt(EXTRA_INPUT_TYPE, DEFAULT_INPUT_TYPE);
                mImeOptions = preference.getExtras().getInt(EXTRA_IME_OPTIONS, DEFAULT_IME_OPTIONS);
            } else {
                throw new IllegalArgumentException("Preference must be a EditTextPreference");
            }
        } else {
            mDialogTitle = savedInstanceState.getCharSequence(SAVE_STATE_TITLE);
            mDialogMessage = savedInstanceState.getCharSequence(SAVE_STATE_MESSAGE);
            mText = savedInstanceState.getCharSequence(SAVE_STATE_TEXT);
            mInputType = savedInstanceState.getInt(SAVE_STATE_INPUT_TYPE, DEFAULT_INPUT_TYPE);
            mImeOptions = savedInstanceState.getInt(SAVE_STATE_IME_OPTIONS, DEFAULT_IME_OPTIONS);
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putCharSequence(SAVE_STATE_TITLE, mDialogTitle);
        outState.putCharSequence(SAVE_STATE_MESSAGE, mDialogMessage);
        outState.putCharSequence(SAVE_STATE_TEXT, mText);
        outState.putInt(SAVE_STATE_INPUT_TYPE, mInputType);
        outState.putInt(SAVE_STATE_IME_OPTIONS, mImeOptions);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        TypedValue tv = new TypedValue();
        getActivity().getTheme().resolveAttribute(
                androidx.preference.R.attr.preferenceTheme, tv, true);
        int theme = tv.resourceId;
        if (theme == 0) {
            // Fallback to default theme.
            theme = R.style.PreferenceThemeOverlayLeanback;
        }
        Context styledContext = new ContextThemeWrapper(getActivity(), theme);
        LayoutInflater styledInflater = inflater.cloneInContext(styledContext);
        View view = styledInflater.inflate(R.layout.leanback_edit_preference_fragment,
                container, false);

        if (!TextUtils.isEmpty(mDialogTitle)) {
            TextView titleView = (TextView) view.findViewById(R.id.decor_title);
            titleView.setText(mDialogTitle);
        }

        if (!TextUtils.isEmpty(mDialogMessage)) {
            TextView messageView = (TextView) view.findViewById(android.R.id.message);
            messageView.setVisibility(View.VISIBLE);
            messageView.setText(mDialogMessage);
        }

        EditText editText = view.findViewById(android.R.id.edit);
        editText.setInputType(mInputType);
        editText.setImeOptions(mImeOptions);
        if (!TextUtils.isEmpty(mText)) {
            editText.setText(mText);
        }
        editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE
                        || actionId == EditorInfo.IME_ACTION_GO
                        || actionId == EditorInfo.IME_ACTION_SEARCH
                        || actionId == EditorInfo.IME_ACTION_NEXT
                        || actionId == EditorInfo.IME_ACTION_SEND) {
                    InputMethodManager imm = (InputMethodManager)
                            getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(textView.getWindowToken(), 0);
                    EditTextPreference preference = (EditTextPreference) getPreference();
                    preference.setText(textView.getText().toString());
                    getFragmentManager().popBackStack();
                    return true;
                }
                return false;
            }
        });

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        EditText editText = getView().findViewById(android.R.id.edit);
        InputMethodManager imm = (InputMethodManager)
                getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        editText.requestFocus();
        imm.showSoftInput(editText, 0);
    }
}