Example usage for android.view ViewGroup findViewById

List of usage examples for android.view ViewGroup findViewById

Introduction

In this page you can find the example usage for android.view ViewGroup findViewById.

Prototype

@Nullable
public final <T extends View> T findViewById(@IdRes int id) 

Source Link

Document

Finds the first descendant view with the given ID, the view itself if the ID matches #getId() , or null if the ID is invalid (< 0) or there is no matching view in the hierarchy.

Usage

From source file:com.chatwing.whitelabel.activities.CommunicationActivity.java

private void styleErrorSnackbar() {
    ViewGroup group = (ViewGroup) snackbar.getView();
    group.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
    snackbar.setActionTextColor(getResources().getColor(R.color.white));
    TextView tv = (TextView) group.findViewById(android.support.design.R.id.snackbar_text);
    tv.setTextColor(getResources().getColor(R.color.white));
}

From source file:com.limewoodmedia.nsdroid.fragments.NavigationDrawerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ViewGroup layout = (ViewGroup) (inflater.inflate(R.layout.fragment_navigation_drawer, container, false));
    MenuItemHolder[] holders = new MenuItemHolder[] {
            new MenuItemHolder(R.id.menu_start, R.drawable.icon_start, R.string.menu_start),
            new MenuItemHolder(R.id.menu_nation, R.drawable.icon_nation, R.string.menu_nation),
            new MenuItemHolder(R.id.submenu_issues, R.drawable.icon_issues, R.string.menu_issues),
            new MenuItemHolder(R.id.submenu_dossier, R.drawable.icon_dossier, R.string.menu_dossier),
            new MenuItemHolder(R.id.menu_region, R.drawable.icon_region, R.string.menu_region),
            new MenuItemHolder(R.id.submenu_rmb, R.drawable.icon_rmb, R.string.menu_rmb),
            new MenuItemHolder(R.id.submenu_officers, R.drawable.icon_officers, R.string.menu_officers),
            new MenuItemHolder(R.id.submenu_embassies, R.drawable.icon_embassies, R.string.menu_embassies),
            new MenuItemHolder(R.id.menu_world, R.drawable.icon_world, R.string.menu_world),
            new MenuItemHolder(R.id.menu_wa, R.drawable.icon_wa, R.string.menu_wa),
            new MenuItemHolder(R.id.menu_news, R.drawable.icon_news, R.string.menu_news),
            new MenuItemHolder(R.id.menu_settings, R.drawable.icon_settings, R.string.menu_settings),
            new MenuItemHolder(R.id.menu_logout, R.drawable.icon_logout, R.string.menu_logout) };
    View view;/*from w  w w .  j a  v  a  2 s.  c o m*/
    for (final MenuItemHolder holder : holders) {
        view = layout.findViewById(holder.viewId);
        if (view == null)
            continue;
        ((ImageView) view.findViewById(R.id.menu_item_image)).setImageResource(holder.imageId);
        ((TextView) view.findViewById(R.id.menu_item_text)).setText(holder.textId);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectMenuItem(holder.viewId);
            }
        });
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    view.setBackgroundColor(getActivity().getResources().getColor(R.color.menu_item_selected));
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_OUTSIDE:
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_HOVER_EXIT:
                case MotionEvent.ACTION_POINTER_UP:
                    view.setBackgroundColor(0x00000000);
                    break;
                }
                return false;
            }
        });
    }
    //      layout.setOnTouchListener(new View.OnTouchListener() {
    //         @Override
    //         public boolean onTouch(View view, MotionEvent motionEvent) {
    //            return true;
    //         }
    //      });
    return layout;
}

From source file:com.example.testtab.fragment.TwitEyesPageFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    /*        // Inflate the layout containing a title and body text.
            ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
            // Set the title view to show the page number.
            ((TextView) rootView.findViewById(android.R.id.text1)).setText(getString(R.string.title_template_step, mPageNumber + 10));
    *///from  w  ww .j  a  va  2 s. c om
    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.tw_main, container, false);

    // TwitEyes OnCreate -------------------------- //
    //        this.mImageView = (ImageView)rootView.findViewById(R.id.image_view);
    // LIST VIEW
    mAdapter = new ArrayAdapter<String>(mContext, R.layout.tw_list_row, new ArrayList<String>());
    //        setListAdapter(mAdapter);

    // INSTANCE
    this.tweet = new ArrayList<CItem>();
    this.idsLimit = 0;
    this.df = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy", Locale.ENGLISH);
    this.handler = new Handler();
    this.lastKickedTime = 0;
    this.lastPercent = 0;
    this.screenName = "";
    this.interval = 0;
    this.isSecure = true;
    this.isRunnable = true;
    modeState = MODE_MAIN;

    // LISTENER
    for (int i = 0; i < imageViews.length; i++) {
        ImageButton iButton = (ImageButton) rootView.findViewById(imageViews[i]);
        iButton.setOnClickListener(this);
        iButton.setOnLongClickListener(this);
    }

    // LOAD SAVE.DAT
    loadGame();

    // OPTION
    //        if (this.screenName.equals("")) kickImageLevelActivity();
    if (this.screenName.equals(""))
        ((Tab3Activity) mContext).kickImageLevelActivity();
    this.mRootView = rootView;
    // TwitEyes OnCreate -------------------------- //

    return rootView;
}

From source file:androidx.media.widget.MediaControlView2.java

@SuppressWarnings("deprecation")
private void initControllerView(ViewGroup v) {
    // Relating to Title Bar View
    mTitleBar = v.findViewById(R.id.title_bar);
    mTitleView = v.findViewById(R.id.title_text);
    mAdExternalLink = v.findViewById(R.id.ad_external_link);
    mBackButton = v.findViewById(R.id.back);
    if (mBackButton != null) {
        mBackButton.setOnClickListener(mBackListener);
        mBackButton.setVisibility(View.GONE);
    }/*from   w  w  w  .j a  v  a2 s  .  c  o m*/
    // TODO (b/77158231) revive
    // mRouteButton = v.findViewById(R.id.cast);

    // Relating to Center View
    mCenterView = v.findViewById(R.id.center_view);
    mTransportControls = inflateTransportControls(R.layout.embedded_transport_controls);
    mCenterView.addView(mTransportControls);

    // Relating to Minimal Extra View
    mMinimalExtraView = (LinearLayout) v.findViewById(R.id.minimal_extra_view);
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mMinimalExtraView.getLayoutParams();
    int iconSize = mResources.getDimensionPixelSize(R.dimen.mcv2_embedded_icon_size);
    int marginSize = mResources.getDimensionPixelSize(R.dimen.mcv2_icon_margin);
    params.setMargins(0, (iconSize + marginSize * 2) * (-1), 0, 0);
    mMinimalExtraView.setLayoutParams(params);
    mMinimalExtraView.setVisibility(View.GONE);

    // Relating to Progress Bar View
    mProgress = v.findViewById(R.id.progress);
    if (mProgress != null) {
        if (mProgress instanceof SeekBar) {
            SeekBar seeker = (SeekBar) mProgress;
            seeker.setOnSeekBarChangeListener(mSeekListener);
            seeker.setProgressDrawable(mResources.getDrawable(R.drawable.custom_progress));
            seeker.setThumb(mResources.getDrawable(R.drawable.custom_progress_thumb));
        }
        mProgress.setMax(MAX_PROGRESS);
    }
    mProgressBuffer = v.findViewById(R.id.progress_buffer);

    // Relating to Bottom Bar View
    mBottomBar = v.findViewById(R.id.bottom_bar);

    // Relating to Bottom Bar Left View
    mBottomBarLeftView = v.findViewById(R.id.bottom_bar_left);
    mTimeView = v.findViewById(R.id.time);
    mEndTime = v.findViewById(R.id.time_end);
    mCurrentTime = v.findViewById(R.id.time_current);
    mAdSkipView = v.findViewById(R.id.ad_skip_time);
    mFormatBuilder = new StringBuilder();
    mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

    // Relating to Bottom Bar Right View
    mBottomBarRightView = v.findViewById(R.id.bottom_bar_right);
    mBasicControls = v.findViewById(R.id.basic_controls);
    mExtraControls = v.findViewById(R.id.extra_controls);
    mCustomButtons = v.findViewById(R.id.custom_buttons);
    mSubtitleButton = v.findViewById(R.id.subtitle);
    if (mSubtitleButton != null) {
        mSubtitleButton.setOnClickListener(mSubtitleListener);
    }
    mFullScreenButton = v.findViewById(R.id.fullscreen);
    if (mFullScreenButton != null) {
        mFullScreenButton.setOnClickListener(mFullScreenListener);
        // TODO: Show Fullscreen button when only it is possible.
    }
    mOverflowButtonRight = v.findViewById(R.id.overflow_right);
    if (mOverflowButtonRight != null) {
        mOverflowButtonRight.setOnClickListener(mOverflowRightListener);
    }
    mOverflowButtonLeft = v.findViewById(R.id.overflow_left);
    if (mOverflowButtonLeft != null) {
        mOverflowButtonLeft.setOnClickListener(mOverflowLeftListener);
    }
    mMuteButton = v.findViewById(R.id.mute);
    if (mMuteButton != null) {
        mMuteButton.setOnClickListener(mMuteButtonListener);
    }
    mSettingsButton = v.findViewById(R.id.settings);
    if (mSettingsButton != null) {
        mSettingsButton.setOnClickListener(mSettingsButtonListener);
    }
    mVideoQualityButton = v.findViewById(R.id.video_quality);
    if (mVideoQualityButton != null) {
        mVideoQualityButton.setOnClickListener(mVideoQualityListener);
    }
    mAdRemainingView = v.findViewById(R.id.ad_remaining);

    // Relating to Settings List View
    initializeSettingsLists();
    mSettingsListView = (ListView) inflateLayout(getContext(), R.layout.settings_list);
    mSettingsAdapter = new SettingsAdapter(mSettingsMainTextsList, mSettingsSubTextsList, mSettingsIconIdsList);
    mSubSettingsAdapter = new SubSettingsAdapter(null, 0);
    mSettingsListView.setAdapter(mSettingsAdapter);
    mSettingsListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    mSettingsListView.setOnItemClickListener(mSettingsItemClickListener);

    mEmbeddedSettingsItemWidth = mResources.getDimensionPixelSize(R.dimen.mcv2_embedded_settings_width);
    mFullSettingsItemWidth = mResources.getDimensionPixelSize(R.dimen.mcv2_full_settings_width);
    mEmbeddedSettingsItemHeight = mResources.getDimensionPixelSize(R.dimen.mcv2_embedded_settings_height);
    mFullSettingsItemHeight = mResources.getDimensionPixelSize(R.dimen.mcv2_full_settings_height);
    mSettingsWindowMargin = (-1) * mResources.getDimensionPixelSize(R.dimen.mcv2_settings_offset);
    mSettingsWindow = new PopupWindow(mSettingsListView, mEmbeddedSettingsItemWidth, LayoutParams.WRAP_CONTENT,
            true);
}

From source file:android.support.transition.FadePort.java

@Override
public Animator onDisappear(ViewGroup sceneRoot, TransitionValues startValues, int startVisibility,
        TransitionValues endValues, int endVisibility) {
    if ((mFadingMode & OUT) != OUT) {
        return null;
    }//from   w ww.  ja  va2  s .c o m
    View view = null;
    View startView = (startValues != null) ? startValues.view : null;
    View endView = (endValues != null) ? endValues.view : null;
    if (DBG) {
        Log.d(LOG_TAG, "Fade.onDisappear: startView, startVis, endView, endVis = " + startView + ", "
                + startVisibility + ", " + endView + ", " + endVisibility);
    }
    View overlayView = null;
    View viewToKeep = null;
    if (endView == null || endView.getParent() == null) {
        if (endView != null) {
            // endView was removed from its parent - add it to the overlay
            view = overlayView = endView;
        } else if (startView != null) {
            // endView does not exist. Use startView only under certain
            // conditions, because placing a view in an overlay necessitates
            // it being removed from its current parent
            if (startView.getParent() == null) {
                // no parent - safe to use
                view = overlayView = startView;
            } else if (startView.getParent() instanceof View && startView.getParent().getParent() == null) {
                View startParent = (View) startView.getParent();
                int id = startParent.getId();
                if (id != View.NO_ID && sceneRoot.findViewById(id) != null && mCanRemoveViews) {
                    // no parent, but its parent is unparented  but the parent
                    // hierarchy has been replaced by a new hierarchy with the same id
                    // and it is safe to un-parent startView
                    view = overlayView = startView;
                }
            }
        }
    } else {
        // visibility change
        if (endVisibility == View.INVISIBLE) {
            view = endView;
            viewToKeep = view;
        } else {
            // Becoming GONE
            if (startView == endView) {
                view = endView;
                viewToKeep = view;
            } else {
                view = startView;
                overlayView = view;
            }
        }
    }
    final int finalVisibility = endVisibility;
    // TODO: add automatic facility to Visibility superclass for keeping views around
    if (overlayView != null) {
        // TODO: Need to do this for general case of adding to overlay
        int screenX = (Integer) startValues.values.get(PROPNAME_SCREEN_X);
        int screenY = (Integer) startValues.values.get(PROPNAME_SCREEN_Y);
        int[] loc = new int[2];
        sceneRoot.getLocationOnScreen(loc);
        ViewCompat.offsetLeftAndRight(overlayView, (screenX - loc[0]) - overlayView.getLeft());
        ViewCompat.offsetTopAndBottom(overlayView, (screenY - loc[1]) - overlayView.getTop());
        ViewGroupOverlay.createFrom(sceneRoot).add(overlayView);
        //            sceneRoot.getOverlay().add(overlayView);
        // TODO: add automatic facility to Visibility superclass for keeping views around
        final float startAlpha = 1;
        float endAlpha = 0;
        final View finalView = view;
        final View finalOverlayView = overlayView;
        final View finalViewToKeep = viewToKeep;
        final ViewGroup finalSceneRoot = sceneRoot;
        final AnimatorListenerAdapter endListener = new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                finalView.setAlpha(startAlpha);
                // TODO: restore view offset from overlay repositioning
                if (finalViewToKeep != null) {
                    finalViewToKeep.setVisibility(finalVisibility);
                }
                if (finalOverlayView != null) {
                    ViewGroupOverlay.createFrom(finalSceneRoot).remove(finalOverlayView);
                    //                        finalSceneRoot.getOverlay().remove(finalOverlayView);
                }
            }
            //
            //                @Override
            //                public void onAnimationPause(Animator animation) {
            //                    if (finalOverlayView != null) {
            //                        finalSceneRoot.getOverlay().remove(finalOverlayView);
            //                    }
            //                }
            //
            //                @Override
            //                public void onAnimationResume(Animator animation) {
            //                    if (finalOverlayView != null) {
            //                        finalSceneRoot.getOverlay().add(finalOverlayView);
            //                    }
            //                }
        };
        return createAnimation(view, startAlpha, endAlpha, endListener);
    }
    if (viewToKeep != null) {
        // TODO: find a different way to do this, like just changing the view to be
        // VISIBLE for the duration of the transition
        viewToKeep.setVisibility((View.VISIBLE));
        // TODO: add automatic facility to Visibility superclass for keeping views around
        final float startAlpha = 1;
        float endAlpha = 0;
        final View finalView = view;
        final View finalOverlayView = overlayView;
        final View finalViewToKeep = viewToKeep;
        final ViewGroup finalSceneRoot = sceneRoot;
        final AnimatorListenerAdapter endListener = new AnimatorListenerAdapter() {
            boolean mCanceled = false;

            float mPausedAlpha = -1;

            //                @Override
            //                public void onAnimationPause(Animator animation) {
            //                    if (finalViewToKeep != null && !mCanceled) {
            //                        finalViewToKeep.setVisibility(finalVisibility);
            //                    }
            //                    mPausedAlpha = finalView.getAlpha();
            //                    finalView.setAlpha(startAlpha);
            //                }
            //
            //                @Override
            //                public void onAnimationResume(Animator animation) {
            //                    if (finalViewToKeep != null && !mCanceled) {
            //                        finalViewToKeep.setVisibility(View.VISIBLE);
            //                    }
            //                    finalView.setAlpha(mPausedAlpha);
            //                }

            @Override
            public void onAnimationCancel(Animator animation) {
                mCanceled = true;
                if (mPausedAlpha >= 0) {
                    finalView.setAlpha(mPausedAlpha);
                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (!mCanceled) {
                    finalView.setAlpha(startAlpha);
                }
                // TODO: restore view offset from overlay repositioning
                if (finalViewToKeep != null && !mCanceled) {
                    finalViewToKeep.setVisibility(finalVisibility);
                }
                if (finalOverlayView != null) {
                    ViewGroupOverlay.createFrom(finalSceneRoot).add(finalOverlayView);
                    //                        finalSceneRoot.getOverlay().remove(finalOverlayView);
                }
            }
        };
        return createAnimation(view, startAlpha, endAlpha, endListener);
    }
    return null;
}

From source file:com.android.launcher2.PagedView.java

protected View getScrollingIndicator() {
    // We use mHasScrollIndicator to prevent future lookups if there is no sibling indicator
    // found// w w  w  .j  a va  2s. c om
    if (mHasScrollIndicator && mScrollIndicator == null) {
        ViewGroup parent = (ViewGroup) getParent();
        if (parent != null) {
            mScrollIndicator = (View) (parent.findViewById(R.id.paged_view_indicator));
            mHasScrollIndicator = mScrollIndicator != null;
            if (mHasScrollIndicator) {
                mScrollIndicator.setVisibility(View.VISIBLE);
            }
        }
    }
    return mScrollIndicator;
}

From source file:com.grokkingandroid.sampleapp.samples.about.AboutFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Resources res = getResources();
    if (getArguments() == null) {
        throw new IllegalStateException("Arguments bundle must not be empty");
    }//w ww.  ja  v  a2s .  com
    int[] resIds = getArguments().getIntArray(KEY_RESOURCE_IDS);
    getDialog().setTitle(res.getString(R.string.about));
    View view = inflater.inflate(R.layout.fragment_about, container, false);
    ViewGroup libParent = (ViewGroup) view.findViewById(R.id.about_container);

    String[] libTitles = null;
    String[] libDescriptions = null;
    if (resIds[0] != -1) {
        libTitles = res.getStringArray(resIds[0]);
        libDescriptions = res.getStringArray(resIds[1]);
    }
    if (getArguments().getBoolean(KEY_ADD_DEFAULT_LIBS, true)) {
        if (resIds[0] == -1) {
            libTitles = res.getStringArray(R.array.grokkingandroidsample_about_titles);
            libDescriptions = res.getStringArray(R.array.grokkingandroidsample_about_contents);
        } else {
            String[] defaultTitles = res.getStringArray(R.array.grokkingandroidsample_about_titles);
            String[] target = new String[defaultTitles.length + libTitles.length];
            System.arraycopy(libTitles, 0, target, 0, libTitles.length);
            System.arraycopy(defaultTitles, 0, target, libTitles.length, defaultTitles.length);
            libTitles = target;
            String[] defaultDescriptions = res.getStringArray(R.array.grokkingandroidsample_about_contents);
            target = new String[defaultDescriptions.length + libTitles.length];
            System.arraycopy(libDescriptions, 0, target, 0, libDescriptions.length);
            System.arraycopy(defaultDescriptions, 0, target, libDescriptions.length,
                    defaultDescriptions.length);
            libDescriptions = target;
        }
    }
    String libraryPlural = res.getQuantityString(R.plurals.plural_libraries, libTitles.length);
    String appTitle = res.getString(resIds[3]);
    String copyrightYear = res.getString(resIds[4]);
    String repositoryLink = res.getString(resIds[5]);
    String aboutText = res.getString(resIds[2], appTitle, copyrightYear, repositoryLink, libraryPlural);
    Spanned spannedAboutText = Html.fromHtml(aboutText);
    TextView aboutTv = (TextView) libParent.findViewById(R.id.about_text);
    aboutTv.setText(spannedAboutText);
    aboutTv.setMovementMethod(LinkMovementMethod.getInstance());

    if (libTitles != null) {
        for (int i = 0; i < libTitles.length; i++) {
            View libContainer = inflater.inflate(R.layout.single_library_layout, libParent, false);
            TextView currLibTitle = (TextView) libContainer.findViewById(R.id.library_title);
            currLibTitle.setText(libTitles[i]);
            TextView currLibDesc = (TextView) libContainer.findViewById(R.id.library_text);
            Spanned spanned = Html.fromHtml(libDescriptions[i]);
            currLibDesc.setText(spanned);
            currLibDesc.setMovementMethod(LinkMovementMethod.getInstance());
            libParent.addView(libContainer);
        }
    }
    return view;
}

From source file:android.support.transition.Transition.java

/**
 * Recursive method that captures values for the given view and the
 * hierarchy underneath it./* w w  w .j  ava  2 s. c o m*/
 * @param sceneRoot The root of the view hierarchy being captured
 * @param start true if this capture is happening before the scene change,
 * false otherwise
 */
void captureValues(ViewGroup sceneRoot, boolean start) {
    if (start) {
        mStartValues.viewValues.clear();
        mStartValues.idValues.clear();
        mStartValues.itemIdValues.clear();
    } else {
        mEndValues.viewValues.clear();
        mEndValues.idValues.clear();
        mEndValues.itemIdValues.clear();
    }
    if (mTargetIds.size() > 0 || mTargets.size() > 0) {
        if (mTargetIds.size() > 0) {
            for (int i = 0; i < mTargetIds.size(); ++i) {
                int id = mTargetIds.get(i);
                View view = sceneRoot.findViewById(id);
                if (view != null) {
                    TransitionValues values = new TransitionValues();
                    values.view = view;
                    if (start) {
                        captureStartValues(values);
                    } else {
                        captureEndValues(values);
                    }
                    if (start) {
                        mStartValues.viewValues.put(view, values);
                        if (id >= 0) {
                            mStartValues.idValues.put(id, values);
                        }
                    } else {
                        mEndValues.viewValues.put(view, values);
                        if (id >= 0) {
                            mEndValues.idValues.put(id, values);
                        }
                    }
                }
            }
        }
        if (mTargets.size() > 0) {
            for (int i = 0; i < mTargets.size(); ++i) {
                View view = mTargets.get(i);
                if (view != null) {
                    TransitionValues values = new TransitionValues();
                    values.view = view;
                    if (start) {
                        captureStartValues(values);
                    } else {
                        captureEndValues(values);
                    }
                    if (start) {
                        mStartValues.viewValues.put(view, values);
                    } else {
                        mEndValues.viewValues.put(view, values);
                    }
                }
            }
        }
    } else {
        captureHierarchy(sceneRoot, start);
    }
}

From source file:gov.wa.wsdot.android.wsdot.ui.home.FavoritesFragment.java

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

    ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_favorites, null);

    // Check preferences and set defaults if none set
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
    orderedViewTypes[0] = settings.getInt("KEY_FIRST_FAVORITES_SECTION", MY_ROUTE_VIEWTYPE);
    orderedViewTypes[1] = settings.getInt("KEY_SECOND_FAVORITES_SECTION", CAMERAS_VIEWTYPE);
    orderedViewTypes[2] = settings.getInt("KEY_THIRD_FAVORITES_SECTION", FERRIES_SCHEDULES_VIEWTYPE);
    orderedViewTypes[3] = settings.getInt("KEY_FOURTH_FAVORITES_SECTION", MOUNTAIN_PASSES_VIEWTYPE);
    orderedViewTypes[4] = settings.getInt("KEY_FIFTH_FAVORITES_SECTION", TRAVEL_TIMES_VIEWTYPE);
    orderedViewTypes[5] = settings.getInt("KEY_SIXTH_FAVORITES_SECTION", LOCATION_VIEWTYPE);
    orderedViewTypes[6] = settings.getInt("KEY_SEVENTH_FAVORITES_SECTION", TOLL_RATE_VIEWTYPE);

    mRecyclerView = root.findViewById(R.id.my_recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(getActivity());
    mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mFavoritesAdapter = new FavItemAdapter();

    mRecyclerView.setAdapter(mFavoritesAdapter);

    // Add swipe dismiss to favorites list items.
    ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0,
            ItemTouchHelper.LEFT) {//from w  ww .ja  va  2 s. c o m

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            if (viewHolder instanceof HeaderViewHolder)
                return 0;
            return super.getSwipeDirs(recyclerView, viewHolder);
        }

        @Override
        public void onSwiped(final RecyclerView.ViewHolder holder, int swipeDir) {

            final String item_id;
            final int viewType = mFavoritesAdapter.getItemViewType(holder.getAdapterPosition());

            //Keeps holders data for undo
            holder.setIsRecyclable(false);

            //get the camera id or tag for the item being removed.
            switch (viewType) {
            case CAMERAS_VIEWTYPE:
                CameraEntity camera = (CameraEntity) mFavoritesAdapter.getItem(holder.getAdapterPosition());
                item_id = String.valueOf(camera.getCameraId());
                break;
            case FERRIES_SCHEDULES_VIEWTYPE:
                FerryScheduleEntity schedule = (FerryScheduleEntity) mFavoritesAdapter
                        .getItem(holder.getAdapterPosition());
                item_id = String.valueOf(schedule.getFerryScheduleId());
                break;
            case TRAVEL_TIMES_VIEWTYPE:
                TravelTimeGroup group = (TravelTimeGroup) mFavoritesAdapter
                        .getItem(holder.getAdapterPosition());
                item_id = String.valueOf(group.trip.getTitle());
                break;
            case MOUNTAIN_PASSES_VIEWTYPE:
                MountainPassEntity pass = (MountainPassEntity) mFavoritesAdapter
                        .getItem(holder.getAdapterPosition());
                item_id = String.valueOf(pass.getPassId());
                break;
            case LOCATION_VIEWTYPE:
                MapLocationEntity location = (MapLocationEntity) mFavoritesAdapter
                        .getItem(holder.getAdapterPosition());
                item_id = String.valueOf(location.getLocationId());
                break;
            case MY_ROUTE_VIEWTYPE:
                MyRouteEntity myRoute = (MyRouteEntity) mFavoritesAdapter.getItem(holder.getAdapterPosition());
                item_id = String.valueOf(myRoute.getMyRouteId());
                break;
            case TOLL_RATE_VIEWTYPE:
                TollRateGroup tollRateGroup = (TollRateGroup) mFavoritesAdapter
                        .getItem((holder.getAdapterPosition()));
                item_id = String.valueOf(tollRateGroup.tollRateSign.getId());
                break;
            default:
                item_id = null;
            }

            mFavoritesAdapter.remove(item_id, viewType);

            // Display snack bar with undo button
            final Snackbar snackbar = Snackbar.make(mRecyclerView, R.string.remove_favorite,
                    Snackbar.LENGTH_LONG);

            snackbar.setAction("UNDO", view -> mFavoritesAdapter.undo(item_id, viewType, holder));
            snackbar.show();
        }
    };

    ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
    itemTouchHelper.attachToRecyclerView(mRecyclerView);

    // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are
    // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity.
    root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));

    swipeRefreshLayout = root.findViewById(R.id.swipe_container);
    swipeRefreshLayout.setOnRefreshListener(this);
    swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_light,
            R.color.holo_orange_light, R.color.holo_red_light);

    mEmptyView = root.findViewById(R.id.empty_list_view);

    viewModel = ViewModelProviders.of(this, viewModelFactory).get(FavoritesViewModel.class);

    viewModel.getFavoriteCameras().observe(this, cameras -> {
        if (cameras != null) {
            if (cameras.size() > 0) {
                mEmptyView.setVisibility(View.GONE);
            }
            mFavoritesAdapter.setCameras(cameras);
        }
    });

    viewModel.getFavoriteFerrySchedules().observe(this, ferrySchedules -> {
        if (ferrySchedules != null) {
            if (ferrySchedules.size() > 0) {
                mEmptyView.setVisibility(View.GONE);
            }
            mFavoritesAdapter.setFerrySchedules(ferrySchedules);
        }
    });

    viewModel.getFavoriteTravelTimes().observe(this, travelTimeGroups -> {
        if (travelTimeGroups != null) {
            if (travelTimeGroups.size() > 0) {
                mEmptyView.setVisibility(View.GONE);
            }
            mFavoritesAdapter.setTravelTimeGroups(travelTimeGroups);
        }
    });

    viewModel.getFavoritePasses().observe(this, passes -> {
        if (passes != null) {
            if (passes.size() > 0) {
                mEmptyView.setVisibility(View.GONE);
            }
            mFavoritesAdapter.setPasses(passes);
        }
    });

    viewModel.getFavoriteMyRoutes().observe(this, myRoutes -> {
        if (myRoutes != null) {
            if (myRoutes.size() > 0) {
                mEmptyView.setVisibility(View.GONE);
            }
            mFavoritesAdapter.setMyRoutes(myRoutes);
        }
    });

    viewModel.getMapLocations().observe(this, mapLocations -> {
        if (mapLocations != null) {
            if (mapLocations.size() > 0) {
                mEmptyView.setVisibility(View.GONE);
            }
            mFavoritesAdapter.setMapLocations(mapLocations);
        }
    });

    viewModel.getFavoriteTollRates().observe(this, tollRateGroups -> {
        if (tollRateGroups != null) {

            if (tollRateGroups.size() > 0) {
                mEmptyView.setVisibility(View.GONE);
            }

            Collections.sort(tollRateGroups, new SortTollGroupByLocation());
            Collections.sort(tollRateGroups, new SortTollGroupByDirection());
            Collections.sort(tollRateGroups, new SortTollGroupByStateRoute());

            mFavoritesAdapter.setTollRates(tollRateGroups);
        }
    });

    viewModel.getFavoritesLoadingTasksCount().observe(this, numTasks -> {
        if (numTasks != null) {

            if (numTasks == 0) {
                swipeRefreshLayout.setRefreshing(false);
            } else if (numTasks < 0) {
                Log.e(TAG, "numTasks in invalid state");
            } else {
                swipeRefreshLayout.setRefreshing(true);
            }
        }
    });

    return root;
}

From source file:de.sourcestream.movieDB.MainActivity.java

/**
 * First configure the Universal Image Downloader,
 * then we set the main layout to be activity_main.xml
 * and we add the slide menu items./*from   ww  w .j  a  va  2  s .co  m*/
 *
 * @param savedInstanceState If non-null, this activity is being re-constructed from a previous saved state as given here.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mTitle = mDrawerTitle = getTitle();

    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
    ViewGroup header = (ViewGroup) getLayoutInflater().inflate(R.layout.drawer_header, null, false);
    ImageView drawerBackButton = (ImageView) header.findViewById(R.id.drawerBackButton);
    drawerBackButton.setOnClickListener(onDrawerBackButton);
    mDrawerList.addHeaderView(header);
    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
    // setting the nav drawer list adapter
    mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, R.id.title, navMenuTitles));

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        toolbar.bringToFront();
    }

    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            toolbar, R.string.app_name, // nav drawer open - description for accessibility
            R.string.app_name // nav drawer close - description for accessibility
    ) {
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            // calling onPrepareOptionsMenu() to show search view
            invalidateOptionsMenu();
            syncState();
        }

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // calling onPrepareOptionsMenu() to hide search view
            invalidateOptionsMenu();
            syncState();
        }

        // updates the title, toolbar transparency and search view
        public void onDrawerSlide(View drawerView, float slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
            if (slideOffset > .55 && !isDrawerOpen) {
                // opening drawer
                // mDrawerTitle is app title
                getSupportActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu();
                isDrawerOpen = true;
            } else if (slideOffset < .45 && isDrawerOpen) {
                // closing drawer
                // mTitle is title of the current view, can be movies, tv shows or movie title
                getSupportActionBar().setTitle(mTitle);
                invalidateOptionsMenu();
                isDrawerOpen = false;
            }
        }

    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    // Get the action bar title to set padding
    TextView titleTextView = null;

    try {
        Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
        f.setAccessible(true);
        titleTextView = (TextView) f.get(toolbar);
    } catch (NoSuchFieldException e) {

    } catch (IllegalAccessException e) {

    }
    if (titleTextView != null) {
        float scale = getResources().getDisplayMetrics().density;
        titleTextView.setPadding((int) scale * 15, 0, 0, 0);
    }

    phone = getResources().getBoolean(R.bool.portrait_only);

    searchDB = new SearchDB(getApplicationContext());

    if (savedInstanceState == null) {
        // Check orientation and lock to portrait if we are on phone
        if (phone) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        // on first time display view for first nav item
        displayView(1);

        // Use hockey module to check for updates
        checkForUpdates();

        // Universal Loader options and configuration.
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
                .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
                .showImageOnLoading(R.drawable.placeholder_default)
                .showImageForEmptyUri(R.drawable.placeholder_default)
                .showImageOnFail(R.drawable.placeholder_default).cacheOnDisk(true).build();
        Context context = this;
        File cacheDir = StorageUtils.getCacheDirectory(context);
        // Create global configuration and initialize ImageLoader with this config
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .diskCache(new UnlimitedDiscCache(cacheDir)) // default
                .defaultDisplayImageOptions(options).build();
        ImageLoader.getInstance().init(config);

        // Check cache size
        long size = 0;
        File[] filesCache = cacheDir.listFiles();
        for (File file : filesCache) {
            size += file.length();
        }
        if (cacheDir.getUsableSpace() < MinFreeSpace || size > CacheSize) {
            ImageLoader.getInstance().getDiskCache().clear();
            searchDB.cleanSuggestionRecords();
        }

    } else {
        oldPos = savedInstanceState.getInt("oldPos");
        currentMovViewPagerPos = savedInstanceState.getInt("currentMovViewPagerPos");
        currentTVViewPagerPos = savedInstanceState.getInt("currentTVViewPagerPos");
        restoreMovieDetailsState = savedInstanceState.getBoolean("restoreMovieDetailsState");
        restoreMovieDetailsAdapterState = savedInstanceState.getBoolean("restoreMovieDetailsAdapterState");
        movieDetailsBundle = savedInstanceState.getParcelableArrayList("movieDetailsBundle");
        castDetailsBundle = savedInstanceState.getParcelableArrayList("castDetailsBundle");
        tvDetailsBundle = savedInstanceState.getParcelableArrayList("tvDetailsBundle");
        currOrientation = savedInstanceState.getInt("currOrientation");
        lastVisitedSimMovie = savedInstanceState.getInt("lastVisitedSimMovie");
        lastVisitedSimTV = savedInstanceState.getInt("lastVisitedSimTV");
        lastVisitedMovieInCredits = savedInstanceState.getInt("lastVisitedMovieInCredits");
        saveInMovieDetailsSimFragment = savedInstanceState.getBoolean("saveInMovieDetailsSimFragment");

        FragmentManager fm = getFragmentManager();
        // prevent the following bug: go to gallery preview -> swap orientation ->
        // go to movies list -> swap orientation -> action bar bugged
        // so if we are not on gallery preview we show toolbar
        if (fm.getBackStackEntryCount() == 0
                || !fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName().equals("galleryList")) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    if (getSupportActionBar() != null && !getSupportActionBar().isShowing())
                        getSupportActionBar().show();
                }
            });
        }
    }

    // Get reference for the imageLoader
    imageLoader = ImageLoader.getInstance();

    // Options used for the backdrop image in movie and tv details and gallery
    optionsWithFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500))
            .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false).showImageOnLoading(R.color.black)
            .showImageForEmptyUri(R.color.black).showImageOnFail(R.color.black).cacheOnDisk(true).build();
    optionsWithoutFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.color.black).showImageForEmptyUri(R.color.black)
            .showImageOnFail(R.color.black).cacheOnDisk(true).build();

    // Options used for the backdrop image in movie and tv details and gallery
    backdropOptionsWithFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500))
            .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.drawable.placeholder_backdrop)
            .showImageForEmptyUri(R.drawable.placeholder_backdrop)
            .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build();
    backdropOptionsWithoutFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.drawable.placeholder_backdrop)
            .showImageForEmptyUri(R.drawable.placeholder_backdrop)
            .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build();

    trailerListView = new TrailerList();
    galleryListView = new GalleryList();

    if (currOrientation != getResources().getConfiguration().orientation)
        orientationChanged = true;

    currOrientation = getResources().getConfiguration().orientation;

    iconConstantSpecialCase = 0;
    if (phone) {
        iconMarginConstant = 0;
        iconMarginLandscape = 0;
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        if (width <= 480 && height <= 800)
            iconConstantSpecialCase = -70;

        // used in MovieDetails, CastDetails, TVDetails onMoreIconClick
        // to check whether the animation should be in up or down direction
        threeIcons = 128;
        threeIconsToolbar = 72;
        twoIcons = 183;
        twoIconsToolbar = 127;
        oneIcon = 238;
        oneIconToolbar = 182;
    } else {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            iconMarginConstant = 232;
            iconMarginLandscape = 300;

            threeIcons = 361;
            threeIconsToolbar = 295;
            twoIcons = 416;
            twoIconsToolbar = 351;
            oneIcon = 469;
            oneIconToolbar = 407;
        } else {
            iconMarginConstant = 82;
            iconMarginLandscape = 0;

            threeIcons = 209;
            threeIconsToolbar = 146;
            twoIcons = 264;
            twoIconsToolbar = 200;
            oneIcon = 319;
            oneIconToolbar = 256;
        }

    }

    dateFormat = android.text.format.DateFormat.getDateFormat(this);
}