Code example for Chronometer

Methods: getLayoutParams, getWidth, requestLayout, stop

0
                "Expecting child ProgressBar with id 'android.R.id.progress'"); 
        } 
         
        // Stop Chronometer if we're past duration 
        long now = SystemClock.elapsedRealtime();
        if (now >= mDurationBase) {
            mChronometer.stop();
        } 
 
        // Update the ProgressBar status 
        int remaining = (int) (mDurationBase - now);
        mProgressBar.setProgress(mDuration - remaining);
         
        // Move the Chronometer if gravity is set correctly 
        if (mChronometerFollow) {
            RelativeLayout.LayoutParams params;
             
            // Calculate estimate of ProgressBar leading edge position 
            params = (RelativeLayout.LayoutParams) mProgressBar.getLayoutParams();
            int contentWidth = mProgressBar.getWidth() - (params.leftMargin + params.rightMargin);
            int leadingEdge = ((contentWidth * mProgressBar.getProgress()) /
                    mProgressBar.getMax()) + params.leftMargin;
             
            // Calculate any adjustment based on gravity 
            int adjustLeft = 0;
            int textWidth = mChronometer.getWidth();
            if (mChronometerGravity == Gravity.END) {
                adjustLeft = -textWidth;
            } else if (mChronometerGravity == Gravity.CENTER_HORIZONTAL) {
                adjustLeft = -(textWidth / 2);
            } 
             
            // Limit margin to keep text inside ProgressBar bounds 
            leadingEdge += adjustLeft;
            int rightLimit = contentWidth - params.rightMargin - textWidth;
            if (leadingEdge < params.leftMargin) {
                leadingEdge = params.leftMargin;
            } else if (leadingEdge > rightLimit) {
                leadingEdge = rightLimit;
            } 
             
            params = (RelativeLayout.LayoutParams) mChronometer.getLayoutParams();
            params.leftMargin = leadingEdge;
             
            // Request layout to move Chronometer 
            mChronometer.requestLayout();
             
        } 
    } 
}