Example usage for java.util Formatter Formatter

List of usage examples for java.util Formatter Formatter

Introduction

In this page you can find the example usage for java.util Formatter Formatter.

Prototype

public Formatter(OutputStream os, String csn) throws UnsupportedEncodingException 

Source Link

Document

Constructs a new formatter with the specified output stream and charset.

Usage

From source file:com.mobilevue.vod.VideoControllerView.java

private void initControllerView(View v) {
    mPauseButton = (ImageButton) v.findViewById(R.id.pause);
    if (mPauseButton != null) {
        mPauseButton.requestFocus();//from   w w w. ja v a2 s  .  c  o m
        mPauseButton.setOnClickListener(mPauseListener);
    }

    /*
     * mFullscreenButton = (ImageButton) v.findViewById(R.id.fullscreen); if
     * (mFullscreenButton != null) { mFullscreenButton.requestFocus();
     * mFullscreenButton.setOnClickListener(mFullscreenListener); }
     */

    mFfwdButton = (ImageButton) v.findViewById(R.id.ffwd);
    if (mFfwdButton != null) {
        mFfwdButton.setOnClickListener(mFfwdListener);
        if (!mFromXml) {
            mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
        }
    }

    mRewButton = (ImageButton) v.findViewById(R.id.rew);
    if (mRewButton != null) {
        mRewButton.setOnClickListener(mRewListener);
        if (!mFromXml) {
            mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
        }
    }

    // By default these are hidden. They will be enabled when
    // setPrevNextListeners() is called
    mNextButton = (ImageButton) v.findViewById(R.id.next);
    if (mNextButton != null && !mFromXml && !mListenersSet) {
        mNextButton.setVisibility(View.GONE);
    }
    mPrevButton = (ImageButton) v.findViewById(R.id.prev);
    if (mPrevButton != null && !mFromXml && !mListenersSet) {
        mPrevButton.setVisibility(View.GONE);
    }

    mProgress = (ProgressBar) v.findViewById(R.id.mediacontroller_progress);
    if (mProgress != null) {
        if (mProgress instanceof SeekBar) {
            SeekBar seeker = (SeekBar) mProgress;
            seeker.setOnSeekBarChangeListener(mSeekListener);
        }
        mProgress.setMax(1000);
    }

    mEndTime = (TextView) v.findViewById(R.id.time);
    mCurrentTime = (TextView) v.findViewById(R.id.time_current);
    mFormatBuilder = new StringBuilder();
    mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

    installPrevNextListeners();

}

From source file:im.neon.adapters.VectorMessagesAdapter.java

/**
 * Converts a difference of days to a string.
 * @param date the date to display//from  ww w  .j  a  va 2s .  c o  m
 * @param nbrDays the number of days between the reference days
 * @return the date text
 */
private String dateDiff(Date date, long nbrDays) {
    if (nbrDays == 0) {
        return mContext.getResources().getString(R.string.today);
    } else if (nbrDays == 1) {
        return mContext.getResources().getString(R.string.yesterday);
    } else if (nbrDays < 7) {
        return (new SimpleDateFormat("EEEE", AdapterUtils.getLocale(mContext))).format(date);
    } else {
        int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_ABBREV_ALL
                | DateUtils.FORMAT_SHOW_WEEKDAY;

        Formatter f = new Formatter(new StringBuilder(50), AdapterUtils.getLocale(mContext));
        return DateUtils.formatDateRange(mContext, f, date.getTime(), date.getTime(), flags).toString();
    }
}

From source file:com.gdgdevfest.android.apps.devfestbcn.ui.MapFragment.java

/**
 * Create an {@link AsyncQueryHandler} for use with the
 * {@link MapInfoWindowAdapter}.// w w w  . j a va 2  s.  c o  m
 */
private AsyncQueryHandler createInfowindowHandler(ContentResolver contentResolver) {
    return new AsyncQueryHandler(contentResolver) {
        StringBuilder mBuffer = new StringBuilder();
        Formatter mFormatter = new Formatter(mBuffer, Locale.getDefault());

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {

            MarkerModel model = mMarkers.get(cookie);

            mInfoAdapter.clearData();

            if (model == null || cursor == null) {
                // query did not complete or incorrect data was loaded
                return;
            }

            final long time = UIUtils.getCurrentTime(getActivity());

            switch (token) {
            case SessionAfterQuery._TOKEN: {
                extractSession(cursor, model, time);
            }
                break;
            case SandboxCompaniesAtQuery._TOKEN: {
                extractSandbox(cursor, model, time);
            }
            }

            // update the displayed window
            model.marker.showInfoWindow();
        }

        private void extractSandbox(Cursor cursor, MarkerModel model, long time) {
            // get tracks data from cache: icon and color
            TrackModel track = mTracks.get(model.track);
            int color = (track != null) ? track.color : 0;
            int iconResId = 0;
            if (track != null) {
                iconResId = getResources().getIdentifier("track_" + ParserUtils.sanitizeId(track.name),
                        "drawable", getActivity().getPackageName());
            }

            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();

                StringBuilder sb = new StringBuilder();
                int count = 0;
                final int maxCompaniesDisplay = getResources()
                        .getInteger(R.integer.sandbox_company_list_max_display);
                while (!cursor.isAfterLast() && count < maxCompaniesDisplay) {
                    if (sb.length() > 0) {
                        sb.append(", ");
                    }
                    sb.append(cursor.getString(SandboxCompaniesAtQuery.COMPANY_NAME));
                    count++;
                    cursor.moveToNext();
                }
                if (count >= maxCompaniesDisplay && !cursor.isAfterLast()) {
                    // Additional sandbox companies to display
                    sb.append(", &hellip;");
                }

                mInfoAdapter.setSandbox(model.marker, model.label, color, iconResId,
                        sb.length() > 0 ? sb.toString() : null);

            } else {
                // No active sandbox companies
                mInfoAdapter.setSandbox(model.marker, model.label, color, iconResId, null);
            }

            model.marker.showInfoWindow();
        }

        private static final long SHOW_UPCOMING_TIME = 24 * 60 * 60 * 1000; // 24 hours

        private void extractSession(Cursor cursor, MarkerModel model, long time) {

            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();

                String currentTitle = null;
                String nextTitle = null;
                String nextTime = null;

                final long blockStart = cursor.getLong(SessionAfterQuery.BLOCK_START);
                final long blockEnd = cursor.getLong(SessionAfterQuery.BLOCK_END);
                boolean inProgress = time >= blockStart && time <= blockEnd;

                if (inProgress) {
                    // A session is running, display its name and optionally
                    // the next session
                    currentTitle = cursor.getString(SessionAfterQuery.SESSION_TITLE);

                    //move to the next entry
                    cursor.moveToNext();
                }

                if (!cursor.isAfterLast()) {
                    //There is a session coming up next, display only it if it's within 24 hours of the current time
                    final long nextStart = cursor.getLong(SessionAfterQuery.BLOCK_START);

                    if (nextStart < time + SHOW_UPCOMING_TIME) {
                        nextTitle = cursor.getString(SessionAfterQuery.SESSION_TITLE);
                        mBuffer.setLength(0);

                        boolean showWeekday = !DateUtils.isToday(blockStart)
                                && !UIUtils.isSameDayDisplay(UIUtils.getCurrentTime(getActivity()), blockStart,
                                        getActivity());

                        nextTime = DateUtils.formatDateRange(getActivity(), mFormatter, blockStart, blockStart,
                                DateUtils.FORMAT_SHOW_TIME | (showWeekday
                                        ? DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY
                                        : 0),
                                PrefUtils.getDisplayTimeZone(getActivity()).getID()).toString();
                    }
                }

                // populate the info window adapter
                mInfoAdapter.setSessionData(model.marker, model.label, currentTitle, nextTitle, nextTime,
                        inProgress);

            } else {
                // No entries, display name of room only
                mInfoAdapter.setMarker(model.marker, model.label);
            }
        }

    };
}

From source file:com.hezaijin.advance.widgets.view.progress.DiscreteSeekBar.java

private String convertValueToMessage(int value) {
    String format = mIndicatorFormatter != null ? mIndicatorFormatter : DEFAULT_FORMATTER;
    if (mFormatter == null || mFormatter.locale().equals(Locale.getDefault())) {
        int bufferSize = format.length() + String.valueOf(mMax).length();
        mFormatter = new Formatter(new StringBuilder(bufferSize), Locale.getDefault());
    }/*  ww w . j  a v a  2 s.c o  m*/
    return mFormatter.format(format, value).toString();
}

From source file:com.acious.android.paginationseekbar.PaginationSeekBar.java

private String convertValueToMessage(int value) {
    String format = mIndicatorFormatter != null ? mIndicatorFormatter : DEFAULT_FORMATTER;
    //We're trying to re-use the Formatter here to avoid too much memory allocations
    //But I'm not completey sure if it's doing anything good... :(
    //Previously, this condition was wrong so the Formatter was always re-created
    //But as I fixed the condition, the formatter started outputting trash characters from previous
    //calls, so I mark the StringBuilder as empty before calling format again.

    //Anyways, I see the memory usage still go up on every call to this method
    //and I have no clue on how to fix that... damn Strings...
    if (mFormatter == null || !mFormatter.locale().equals(Locale.getDefault())) {
        int bufferSize = format.length() + String.valueOf(mMax).length();
        if (mFormatBuilder == null) {
            mFormatBuilder = new StringBuilder(bufferSize);
        } else {//w  w w . j  a  v a2  s .com
            mFormatBuilder.ensureCapacity(bufferSize);
        }
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
    } else {
        mFormatBuilder.setLength(0);
    }
    return mFormatter.format(format, value).toString();
}

From source file:com.knowbout.epg.entities.Program.java

@SuppressWarnings("unchecked")
private static Program createMissingTeam(Session session, String sportName, String teamName) {
    log.debug("Calling createMissingTeam()");
    boolean commit = false;
    if (TransactionManager.currentTransaction() == null) {
        TransactionManager.beginTransaction();
        commit = true;//w  w  w .  ja  v  a 2 s  .  c  om
    }
    try {
        Query query = session.getNamedQuery("Program.selectProgramsWithTeam");
        query.setString("programTitle", sportName);
        String episodeTitleLike = "%" + teamName + "%";
        query.setString("episodeTitleLike", episodeTitleLike);
        query.setMaxResults(1);
        List<Program> programs = query.list();
        if (programs == null || programs.size() == 0) {
            return null;
        }

        query = session.createQuery("select MAX(programId) from Program");
        String maxProgramId = (String) query.uniqueResult();
        String teamId = null;
        if (maxProgramId != null && maxProgramId.startsWith("TE")) {
            StringBuilder sb = new StringBuilder();
            Formatter formatter = new Formatter(sb, Locale.US);
            formatter.format("TE%08d0000", Integer.valueOf(maxProgramId.substring(2, 10)) + 1);
            teamId = sb.toString();
        } else {
            teamId = "TE000000010000";
        }

        Program sample = programs.get(0);
        Program team = new Program();
        team.setAdultSituationsAdvisory(sample.getAdultSituationsAdvisory());
        team.setAltSynEpiNum("");
        team.setAltTitle("");
        team.setBriefNudityAdvisory(sample.getBriefNudityAdvisory());
        team.setColorCode(sample.getColorCode());
        team.setDescription("Games played by the " + teamName);
        team.setDescriptionActors(team.getDescription());
        team.setEpisodeTitle(sportName);
        team.setGenreDescription(sample.getGenreDescription());
        team.setGraphicLanguageAdvisory(sample.getGraphicLanguageAdvisory());
        team.setGraphicViolenceAdvisory(sample.getGraphicViolenceAdvisory());
        team.setHoliday("");
        team.setProgramId(teamId);
        team.setLastModified(new Date());
        team.setMadeForTv(sample.isMadeForTv());
        team.setMpaaRating("");
        team.setNetSynSource(sample.getNetSynSource());
        team.setNetSynType(sample.getNetSynType());
        team.setOrgCountry(sample.getOrgCountry());
        team.setOrginalAirDate(null);
        team.setOrgStudio(sample.getOrgStudio());
        team.setProgramLanguage(sample.getProgramLanguage());
        team.setRapeAdvisory(sample.getRapeAdvisory());
        team.setReducedDescription120(truncateWithDots(120, team.getDescription()));
        team.setReducedDescription60("Games played by this team.");
        team.setReducedDescription40("Games played by this team.");
        team.setReducedDescriptionActors("Games played by this team.");
        team.setReducedTitle10(teamName.length() > 10 ? teamName.substring(0, 10) : teamName);
        team.setReducedTitle20(teamName.length() > 20 ? teamName.substring(0, 20) : teamName);
        team.setReducedTitle40(teamName.length() > 40 ? teamName.substring(0, 40) : teamName);
        team.setReducedTitle70(teamName.length() > 70 ? teamName.substring(0, 70) : teamName);
        team.setRunTime(sample.getRunTime());
        team.setShowType(sample.getShowType());
        team.setSourceType(sample.getSourceType());
        team.setSscAdvisory(sample.getSscAdvisory());
        team.setStarRating(sample.getStarRating());
        team.setSynEpiNum(null);
        team.setProgramTitle(teamName);
        team.setUniqueId("");
        team.setYear(null);
        team.insert();
        if (commit) {
            TransactionManager.commitTransaction();
        }

        return team;
    } catch (Error e) {
        log.error("Could not create TEam", e);
        TransactionManager.rollbackTransaction();
        throw e;
    }
}

From source file:fr.cs.examples.propagation.DSSTPropagation.java

/** Print the results in the output file
 *
 *  @param handler orbit handler//from www.  j  a v a 2s  . c o  m
 *  @param output output file
 *  @param sart start date of propagation
 *  @throws OrekitException 
 *  @throws IOException 
 */
private void printOutput(final File output, final OrbitHandler handler, final AbsoluteDate start)
        throws OrekitException, IOException {
    // Output format:
    // time_from_start, a, e, i, raan, pa, aM, h, k, p, q, lM, px, py, pz, vx, vy, vz
    final String format = new String(
            " %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e %24.16e");
    final BufferedWriter buffer = new BufferedWriter(new FileWriter(output));
    buffer.write(
            "##   time_from_start(s)            a(km)                      e                      i(deg)         ");
    buffer.write(
            "         raan(deg)                pa(deg)              mean_anomaly(deg)              ey/h          ");
    buffer.write(
            "           ex/k                    hy/p                     hx/q             mean_longitude_arg(deg)");
    buffer.write(
            "       Xposition(km)           Yposition(km)             Zposition(km)           Xvelocity(km/s)    ");
    buffer.write("      Yvelocity(km/s)         Zvelocity(km/s)");
    buffer.newLine();
    for (Orbit o : handler.getOrbits()) {
        final Formatter f = new Formatter(new StringBuilder(), Locale.ENGLISH);
        // Time from start (s)
        final double time = o.getDate().durationFrom(start);
        // Semi-major axis (km)
        final double a = o.getA() / 1000.;
        // Keplerian elements
        // Eccentricity
        final double e = o.getE();
        // Inclination (degrees)
        final double i = Math.toDegrees(MathUtils.normalizeAngle(o.getI(), FastMath.PI));
        // Right Ascension of Ascending Node (degrees)
        KeplerianOrbit ko = new KeplerianOrbit(o);
        final double ra = Math
                .toDegrees(MathUtils.normalizeAngle(ko.getRightAscensionOfAscendingNode(), FastMath.PI));
        // Perigee Argument (degrees)
        final double pa = Math.toDegrees(MathUtils.normalizeAngle(ko.getPerigeeArgument(), FastMath.PI));
        // Mean Anomaly (degrees)
        final double am = Math
                .toDegrees(MathUtils.normalizeAngle(ko.getAnomaly(PositionAngle.MEAN), FastMath.PI));
        // Equinoctial elements
        // ey/h component of eccentricity vector
        final double h = o.getEquinoctialEy();
        // ex/k component of eccentricity vector
        final double k = o.getEquinoctialEx();
        // hy/p component of inclination vector
        final double p = o.getHy();
        // hx/q component of inclination vector
        final double q = o.getHx();
        // Mean Longitude Argument (degrees)
        final double lm = Math.toDegrees(MathUtils.normalizeAngle(o.getLM(), FastMath.PI));
        // Cartesian elements
        // Position along X in inertial frame (km)
        final double px = o.getPVCoordinates().getPosition().getX() / 1000.;
        // Position along Y in inertial frame (km)
        final double py = o.getPVCoordinates().getPosition().getY() / 1000.;
        // Position along Z in inertial frame (km)
        final double pz = o.getPVCoordinates().getPosition().getZ() / 1000.;
        // Velocity along X in inertial frame (km/s)
        final double vx = o.getPVCoordinates().getVelocity().getX() / 1000.;
        // Velocity along Y in inertial frame (km/s)
        final double vy = o.getPVCoordinates().getVelocity().getY() / 1000.;
        // Velocity along Z in inertial frame (km/s)
        final double vz = o.getPVCoordinates().getVelocity().getZ() / 1000.;
        buffer.write(
                f.format(format, time, a, e, i, ra, pa, am, h, k, p, q, lm, px, py, pz, vx, vy, vz).toString());
        buffer.newLine();
        f.close();
    }
    buffer.close();
}

From source file:edu.berkeley.compbio.sequtils.strings.MarkovTreeNode.java

public String toLongString() {
    final StringBuffer sb = new StringBuffer();
    final Formatter formatter = new Formatter(sb, Locale.US);
    appendString(formatter, "");
    return sb.toString();
}

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);
    }//  w w  w .  ja  va2  s  . com
    // 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:im.ene.lab.toro.ext.layeredvideo.PlaybackControlLayer.java

/**
 * Perform binding to UI, setup of event handlers and initialization of values.
 *//*from  w  ww .  j  a va2s . c om*/
private void setupView() {
    if (actionToolbar == null) {
        actionToolbar = (Toolbar) view.findViewById(R.id.playback_toolbar);
        actionToolbar.inflateMenu(R.menu.playback_actions);
        actionToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (settingsCallback != null) {
                    settingsCallback.onSettings();
                    return true;
                }

                return false;
            }
        });
    }
    // Bind fields to UI elements.
    pausePlayButton = (ImageButton) view.findViewById(R.id.pause);
    fullscreenButton = (ImageButton) view.findViewById((R.id.fullscreen));
    seekBar = (SeekBar) view.findViewById(R.id.media_controller_progress);
    endTime = (TextView) view.findViewById(R.id.time_duration);
    currentTime = (TextView) view.findViewById(R.id.time_current);
    logoImageView = (ImageView) view.findViewById(R.id.logo_image);
    playbackControlRootView = (FrameLayout) view.findViewById(R.id.middle_section);
    topChrome = (RelativeLayout) view.findViewById(R.id.top_chrome);
    bottomChrome = (LinearLayout) view.findViewById(R.id.bottom_chrome);
    actionButtonsContainer = (LinearLayout) view.findViewById(R.id.actions_container);

    // The play button should toggle play/pause when the play/pause button is clicked.
    pausePlayButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            togglePlayPause();
            show(DEFAULT_TIMEOUT_MS);
        }
    });

    if (fullscreenCallback == null) {
        fullscreenButton.setVisibility(View.INVISIBLE);
    }
    // Go into fullscreen when the fullscreen button is clicked.
    fullscreenButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            doToggleFullscreen();
            show(DEFAULT_TIMEOUT_MS);
            updateActionButtons();
            updateColors();
        }
    });

    seekBar.setMax(1000);

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromuser) {
            if (!fromuser || !canSeek) {
                // Ignore programmatic changes to seek bar position.
                // Ignore changes to seek bar position is seeking is not enabled.
                return;
            }

            ObservablePlayerControl playerControl = layerManager.getControl();
            long duration = playerControl.getDuration();
            long newPosition = (duration * progress) / 1000L;
            playerControl.seekTo((int) newPosition);
            if (currentTime != null) {
                currentTime.setText(formatTimeString((int) newPosition));
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            show(0);
            isSeekBarDragging = true;
            handler.removeMessages(SHOW_PROGRESS);
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            isSeekBarDragging = false;
            updateProgress();
            updatePlayPauseButton();
            show(DEFAULT_TIMEOUT_MS);

            handler.sendEmptyMessage(SHOW_PROGRESS);
        }
    });

    actionToolbar.setTitle(videoTitle);

    timeFormat = new StringBuilder();
    timeFormatter = new Formatter(timeFormat, Locale.getDefault());
}