ProgressBar

来源:互联网 发布:阿里云 香港vps 翻墙 编辑:程序博客网 时间:2024/06/05 19:27
Android APIs
Added in API level 1
public class

ProgressBar

extends View
java.lang.Object   ↳android.view.View    ↳android.widget.ProgressBarKnown Direct Subclasses
Known Indirect Subclasses

Class Overview


Visual indicator of progress in some operation. Displays a bar to the user representing how far the operation has progressed; the application can change the amount of progress (modifying the length of the bar) as it moves forward. There is also a secondary progress displayable on a progress bar which is useful for displaying intermediate progress, such as the buffer level during a streaming playback progress bar.

A progress bar can also be made indeterminate. In indeterminate mode, the progress bar shows a cyclic animation without an indication of progress. This mode is used by applications when the length of the task is unknown. The indeterminate progress bar can be either a spinning wheel or a horizontal bar.

The following code example shows how a progress bar can be used from a worker thread to update the user interface to notify the user of progress:

 public class MyActivity extends Activity {     private static final int PROGRESS = 0x1;     private ProgressBar mProgress;     private int mProgressStatus = 0;     private Handler mHandler = new Handler();     protected void onCreate(Bundle icicle) {         super.onCreate(icicle);         setContentView(R.layout.progressbar_activity);         mProgress = (ProgressBar) findViewById(R.id.progress_bar);         // Start lengthy operation in a background thread         new Thread(new Runnable() {             public void run() {                 while (mProgressStatus < 100) {                     mProgressStatus = doWork();                     // Update the progress bar                     mHandler.post(new Runnable() {                         public void run() {                             mProgress.setProgress(mProgressStatus);                         }                     });                 }             }         }).start();     } }

To add a progress bar to a layout file, you can use the <ProgressBar> element. By default, the progress bar is a spinning wheel (an indeterminate indicator). To change to a horizontal progress bar, apply theWidget.ProgressBar.Horizontal style, like so:

 <ProgressBar     style="@android:style/Widget.ProgressBar.Horizontal"     ... />

If you will use the progress bar to show real progress, you must use the horizontal bar. You can then increment the progress withincrementProgressBy() orsetProgress(). By default, the progress bar is full when it reaches 100. If necessary, you can adjust the maximum value (the value for a full bar) using the android:max attribute. Other attributes available are listed below.

Another common style to apply to the progress bar is Widget.ProgressBar.Small, which shows a smaller version of the spinning wheel—useful when waiting for content to load. For example, you can insert this kind of progress bar into your default layout for a view that will be populated by some content fetched from the Internet—the spinning wheel appears immediately and when your application receives the content, it replaces the progress bar with the loaded content. For example:

 <LinearLayout     android:orientation="horizontal"     ... >     <ProgressBar         android:layout_width="wrap_content"         android:layout_height="wrap_content"         style="@android:style/Widget.ProgressBar.Small"         android:layout_marginRight="5dp" />     <TextView         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:text="@string/loading" /> </LinearLayout>

Other progress bar styles provided by the system include:

  • Widget.ProgressBar.Horizontal
  • Widget.ProgressBar.Small
  • Widget.ProgressBar.Large
  • Widget.ProgressBar.Inverse
  • Widget.ProgressBar.Small.Inverse
  • Widget.ProgressBar.Large.Inverse

The "inverse" styles provide an inverse color scheme for the spinner, which may be necessary if your application uses a light colored theme (a white background).

XML attributes

See ProgressBar Attributes,View Attributes

Summary


XML AttributesAttribute NameRelated MethodDescriptionandroid:animationResolution Timeout between frames of animation in milliseconds

Must be an integer value, such as "100". 

android:indeterminate Allows to enable the indeterminate mode. android:indeterminateBehavior Defines how the indeterminate mode should behave when the progress reaches max. android:indeterminateDrawable Drawable used for the indeterminate mode. android:indeterminateDuration Duration of the indeterminate animation. android:indeterminateOnly Restricts to ONLY indeterminate mode (state-keeping progress mode will not work). android:interpolator  android:max Defines the maximum value the progress can take. android:maxHeight An optional argument to supply a maximum height for this view. android:maxWidth An optional argument to supply a maximum width for this view. android:minHeight  android:minWidth  android:mirrorForRtl Defines if the associated drawables need to be mirrored when in RTL mode. android:progress Defines the default progress value, between 0 and max. android:progressDrawable Drawable used for the progress mode. android:secondaryProgress Defines the secondary progress value, between 0 and max. [Expand]
Inherited XML Attributes
From classandroid.view.View
[Expand]
Inherited Constants
From classandroid.view.View
[Expand]
Inherited Fields
From classandroid.view.View
Public ConstructorsProgressBar(Context context)
Create a new progress bar with range 0...100 and initial progress of 0.
ProgressBar(Context context, AttributeSet attrs)ProgressBar(Context context, AttributeSet attrs, int defStyle)Public MethodsDrawablegetIndeterminateDrawable()

Get the drawable used to draw the progress bar in indeterminate mode.

InterpolatorgetInterpolator()
Gets the acceleration curve type for the indeterminate animation.
synchronized intgetMax()

Return the upper limit of this progress bar's range.

synchronized intgetProgress()

Get the progress bar's current level of progress.

DrawablegetProgressDrawable()

Get the drawable used to draw the progress bar in progress mode.

synchronized intgetSecondaryProgress()

Get the progress bar's current level of secondary progress.

synchronized final voidincrementProgressBy(int diff)

Increase the progress bar's progress by the specified amount.

synchronized final voidincrementSecondaryProgressBy(int diff)

Increase the progress bar's secondary progress by the specified amount.

voidinvalidateDrawable(Drawable dr)
Invalidates the specified Drawable.
synchronized booleanisIndeterminate()

Indicate whether this progress bar is in indeterminate mode.

voidjumpDrawablesToCurrentState()
Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.
voidonInitializeAccessibilityEvent(AccessibilityEvent event)
Initializes an AccessibilityEvent with information about this View which is the event source.
voidonInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info)
Initializes an AccessibilityNodeInfo with information about this view.
voidonRestoreInstanceState(Parcelable state)
Hook allowing a view to re-apply a representation of its internal state that had previously been generated byonSaveInstanceState().
ParcelableonSaveInstanceState()
Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state.
voidpostInvalidate()

Cause an invalidate to happen on a subsequent cycle through the event loop.

synchronized voidsetIndeterminate(boolean indeterminate)

Change the indeterminate mode for this progress bar.

voidsetIndeterminateDrawable(Drawable d)

Define the drawable used to draw the progress bar in indeterminate mode.

voidsetInterpolator(Context context, int resID)
Sets the acceleration curve for the indeterminate animation.
voidsetInterpolator(Interpolator interpolator)
Sets the acceleration curve for the indeterminate animation.
synchronized voidsetMax(int max)

Set the range of the progress bar to 0...

synchronized voidsetProgress(int progress)

Set the current progress to the specified value.

voidsetProgressDrawable(Drawable d)

Define the drawable used to draw the progress bar in progress mode.

synchronized voidsetSecondaryProgress(int secondaryProgress)

Set the current secondary progress to the specified value.

voidsetVisibility(int v)
Set the enabled state of this view.
Protected MethodsvoiddrawableStateChanged()
This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.
voidonAttachedToWindow()
This is called when the view is attached to a window.
voidonDetachedFromWindow()
This is called when the view is detached from a window.
synchronized voidonDraw(Canvas canvas)
Implement this to do your drawing.
synchronized voidonMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

voidonSizeChanged(int w, int h, int oldw, int oldh)
This is called during layout when the size of this view has changed.
voidonVisibilityChanged(View changedView, int visibility)
Called when the visibility of the view or an ancestor of the view is changed.
booleanverifyDrawable(Drawable who)
If your view subclass is displaying its own Drawable objects, it should override this function and return true for any Drawable it is displaying.
[Expand]
Inherited Methods
From class android.view.View
From class java.lang.Object
From interface android.graphics.drawable.Drawable.Callback
From interface android.view.KeyEvent.Callback
From interface android.view.accessibility.AccessibilityEventSource

XML Attributes


android:animationResolution

Timeout between frames of animation in milliseconds

Must be an integer value, such as "100".

This may also be a reference to a resource (in the form"@[package:]type:name") ortheme attribute (in the form"?[package:][type:]name")containing a value of this type.

This corresponds to the global attribute resource symbol animationResolution.

Related Methods

android:indeterminate

Allows to enable the indeterminate mode. In this mode the progress bar plays an infinite looping animation.

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form"@[package:]type:name") ortheme attribute (in the form"?[package:][type:]name")containing a value of this type.

This corresponds to the global attribute resource symbol indeterminate.

Related Methods

android:indeterminateBehavior

Defines how the indeterminate mode should behave when the progress reaches max.

Must be one of the following constant values.

ConstantValueDescriptionrepeat1Progress starts over from 0.cycle2Progress keeps the current value and goes back to 0.

This corresponds to the global attribute resource symbol indeterminateBehavior.

Related Methods

android:indeterminateDrawable

Drawable used for the indeterminate mode.

Must be a reference to another resource, in the form "@[+][package:]type:name"or to a theme attribute in the form "?[package:][type:]name".

This corresponds to the global attribute resource symbol indeterminateDrawable.

Related Methods

android:indeterminateDuration

Duration of the indeterminate animation.

Must be an integer value, such as "100".

This may also be a reference to a resource (in the form"@[package:]type:name") ortheme attribute (in the form"?[package:][type:]name")containing a value of this type.

This corresponds to the global attribute resource symbol indeterminateDuration.

Related Methods

android:indeterminateOnly

Restricts to ONLY indeterminate mode (state-keeping progress mode will not work).

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form"@[package:]type:name") ortheme attribute (in the form"?[package:][type:]name")containing a value of this type.

This corresponds to the global attribute resource symbol indeterminateOnly.

Related Methods

android:interpolator

Related Methods

android:max

Defines the maximum value the progress can take.

Must be an integer value, such as "100".

This may also be a reference to a resource (in the form"@[package:]type:name") ortheme attribute (in the form"?[package:][type:]name")containing a value of this type.

This corresponds to the global attribute resource symbol max.

Related Methods

android:maxHeight

An optional argument to supply a maximum height for this view. See {see android.widget.ImageView#setMaxHeight} for details.

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp".Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),in (inches), mm (millimeters).

This may also be a reference to a resource (in the form"@[package:]type:name") ortheme attribute (in the form"?[package:][type:]name")containing a value of this type.

This corresponds to the global attribute resource symbol maxHeight.

Related Methods

android:maxWidth

An optional argument to supply a maximum width for this view. See {see android.widget.ImageView#setMaxWidth} for details.

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp".Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),in (inches), mm (millimeters).

This may also be a reference to a resource (in the form"@[package:]type:name") ortheme attribute (in the form"?[package:][type:]name")containing a value of this type.

This corresponds to the global attribute resource symbol maxWidth.

Related Methods

android:minHeight

Related Methods

android:minWidth

Related Methods

android:mirrorForRtl

Defines if the associated drawables need to be mirrored when in RTL mode. Default is false

Must be a boolean value, either "true" or "false".

This may also be a reference to a resource (in the form"@[package:]type:name") ortheme attribute (in the form"?[package:][type:]name")containing a value of this type.

This corresponds to the global attribute resource symbol mirrorForRtl.

Related Methods

android:progress

Defines the default progress value, between 0 and max.

Must be an integer value, such as "100".

This may also be a reference to a resource (in the form"@[package:]type:name") ortheme attribute (in the form"?[package:][type:]name")containing a value of this type.

This corresponds to the global attribute resource symbol progress.

Related Methods

android:progressDrawable

Drawable used for the progress mode.

Must be a reference to another resource, in the form "@[+][package:]type:name"or to a theme attribute in the form "?[package:][type:]name".

This corresponds to the global attribute resource symbol progressDrawable.

Related Methods

android:secondaryProgress

Defines the secondary progress value, between 0 and max. This progress is drawn between the primary progress and the background. It can be ideal for media scenarios such as showing the buffering progress while the default progress shows the play progress.

Must be an integer value, such as "100".

This may also be a reference to a resource (in the form"@[package:]type:name") ortheme attribute (in the form"?[package:][type:]name")containing a value of this type.

This corresponds to the global attribute resource symbol secondaryProgress.

Related Methods

Public Constructors


public ProgressBar(Context context)

Added in API level 1

Create a new progress bar with range 0...100 and initial progress of 0.

Parameters
contextthe application environment

public ProgressBar(Context context,AttributeSet attrs)

Added in API level 1

public ProgressBar(Context context,AttributeSet attrs, int defStyle)

Added in API level 1

Public Methods


public Drawable getIndeterminateDrawable ()

Added in API level 1

Get the drawable used to draw the progress bar in indeterminate mode.

Returns
  • a Drawable instance
See Also
  • setIndeterminateDrawable(android.graphics.drawable.Drawable)
  • setIndeterminate(boolean)

public Interpolator getInterpolator ()

Added in API level 1

Gets the acceleration curve type for the indeterminate animation.

Returns
  • the Interpolator associated to this animation

public synchronized int getMax ()

Added in API level 1

Return the upper limit of this progress bar's range.

Returns
  • a positive integer
See Also
  • setMax(int)
  • getProgress()
  • getSecondaryProgress()

public synchronized int getProgress ()

Added in API level 1

Get the progress bar's current level of progress. Return 0 when the progress bar is in indeterminate mode.

Returns
  • the current progress, between 0 and getMax()
See Also
  • setIndeterminate(boolean)
  • isIndeterminate()
  • setProgress(int)
  • setMax(int)
  • getMax()

public Drawable getProgressDrawable ()

Added in API level 1

Get the drawable used to draw the progress bar in progress mode.

Returns
  • a Drawable instance
See Also
  • setProgressDrawable(android.graphics.drawable.Drawable)
  • setIndeterminate(boolean)

public synchronized int getSecondaryProgress ()

Added in API level 1

Get the progress bar's current level of secondary progress. Return 0 when the progress bar is in indeterminate mode.

Returns
  • the current secondary progress, between 0 and getMax()
See Also
  • setIndeterminate(boolean)
  • isIndeterminate()
  • setSecondaryProgress(int)
  • setMax(int)
  • getMax()

public final synchronized void incrementProgressBy (int diff)

Added in API level 1

Increase the progress bar's progress by the specified amount.

Parameters
diffthe amount by which the progress must be increased
See Also
  • setProgress(int)

public final synchronized void incrementSecondaryProgressBy (int diff)

Added in API level 1

Increase the progress bar's secondary progress by the specified amount.

Parameters
diffthe amount by which the secondary progress must be increased
See Also
  • setSecondaryProgress(int)

public void invalidateDrawable(Drawable dr)

Added in API level 1

Invalidates the specified Drawable.

Parameters
drthe drawable to invalidate

public synchronized boolean isIndeterminate ()

Added in API level 1

Indicate whether this progress bar is in indeterminate mode.

Returns
  • true if the progress bar is in indeterminate mode

public void jumpDrawablesToCurrentState()

Added in API level 11

Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.

public void onInitializeAccessibilityEvent(AccessibilityEvent event)

Added in API level 14

Initializes an AccessibilityEvent with information about this View which is the event source. In other words, the source of an accessibility event is the view whose state change triggered firing the event.

Example: Setting the password property of an event in addition to properties set by the super implementation:

 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {     super.onInitializeAccessibilityEvent(event);     event.setPassword(true); }

If an View.AccessibilityDelegate has been specified via callingsetAccessibilityDelegate(AccessibilityDelegate) itsonInitializeAccessibilityEvent(View, AccessibilityEvent) is responsible for handling this call.

Note: Always call the super implementation before adding information to the event, in case the default implementation has basic information to add.

Parameters
eventThe event to initialize.

public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info)

Added in API level 14

Initializes an AccessibilityNodeInfo with information about this view. The base implementation sets:

  • setParent(View),
  • setBoundsInParent(Rect),
  • setBoundsInScreen(Rect),
  • setPackageName(CharSequence),
  • setClassName(CharSequence),
  • setContentDescription(CharSequence),
  • setEnabled(boolean),
  • setClickable(boolean),
  • setFocusable(boolean),
  • setFocused(boolean),
  • setLongClickable(boolean),
  • setSelected(boolean),

Subclasses should override this method, call the super implementation, and set additional attributes.

If an View.AccessibilityDelegate has been specified via callingsetAccessibilityDelegate(AccessibilityDelegate) itsonInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo) is responsible for handling this call.

Parameters
infoThe instance to initialize.

public void onRestoreInstanceState(Parcelable state)

Added in API level 1

Hook allowing a view to re-apply a representation of its internal state that had previously been generated byonSaveInstanceState(). This function will never be called with a null state.

Parameters
stateThe frozen state that had previously been returned by onSaveInstanceState().

public Parcelable onSaveInstanceState ()

Added in API level 1

Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

Some examples of things you may store here: the current cursor position in a text view (but usually not the text itself since that is stored in a content provider or other persistent storage), the currently selected item in a list view.

Returns
  • Returns a Parcelable object containing the view's current dynamic state, or null if there is nothing interesting to save. The default implementation returns null.

public void postInvalidate()

Added in API level 1

Cause an invalidate to happen on a subsequent cycle through the event loop. Use this to invalidate the View from a non-UI thread.

This method can be invoked from outside of the UI thread only when this View is attached to a window.

public synchronized void setIndeterminate (boolean indeterminate)

Added in API level 1

Change the indeterminate mode for this progress bar. In indeterminate mode, the progress is ignored and the progress bar shows an infinite animation instead.

If this progress bar's style only supports indeterminate mode (such as the circular progress bars), then this will be ignored.
Parameters
indeterminatetrue to enable the indeterminate mode

public void setIndeterminateDrawable(Drawable d)

Added in API level 1

Define the drawable used to draw the progress bar in indeterminate mode.

Parameters
dthe new drawable
See Also
  • getIndeterminateDrawable()
  • setIndeterminate(boolean)

public void setInterpolator(Context context, int resID)

Added in API level 1

Sets the acceleration curve for the indeterminate animation. The interpolator is loaded as a resource from the specified context.

Parameters
contextThe application environmentresIDThe resource identifier of the interpolator to load

public void setInterpolator(Interpolator interpolator)

Added in API level 1

Sets the acceleration curve for the indeterminate animation. Defaults to a linear interpolation.

Parameters
interpolatorThe interpolator which defines the acceleration curve

public synchronized void setMax (int max)

Added in API level 1

Set the range of the progress bar to 0...max.

Parameters
maxthe upper range of this progress bar
See Also
  • getMax()
  • setProgress(int)
  • setSecondaryProgress(int)

public synchronized void setProgress (int progress)

Added in API level 1

Set the current progress to the specified value. Does not do anything if the progress bar is in indeterminate mode.

Parameters
progressthe new progress, between 0 and getMax()
See Also
  • setIndeterminate(boolean)
  • isIndeterminate()
  • getProgress()
  • incrementProgressBy(int)

public void setProgressDrawable(Drawable d)

Added in API level 1

Define the drawable used to draw the progress bar in progress mode.

Parameters
dthe new drawable
See Also
  • getProgressDrawable()
  • setIndeterminate(boolean)

public synchronized void setSecondaryProgress (int secondaryProgress)

Added in API level 1

Set the current secondary progress to the specified value. Does not do anything if the progress bar is in indeterminate mode.

Parameters
secondaryProgressthe new secondary progress, between 0 and getMax()
See Also
  • setIndeterminate(boolean)
  • isIndeterminate()
  • getSecondaryProgress()
  • incrementSecondaryProgressBy(int)

public void setVisibility(int v)

Added in API level 1

Set the enabled state of this view.

Parameters
vOne of VISIBLE,INVISIBLE, orGONE.

Protected Methods


protected void drawableStateChanged()

Added in API level 1

This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.

Be sure to call through to the superclass when overriding this function.

protected void onAttachedToWindow()

Added in API level 1

This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called beforeonDraw(android.graphics.Canvas), however it may be called any time before the first onDraw -- including before or afteronMeasure(int, int).

protected void onDetachedFromWindow()

Added in API level 1

This is called when the view is detached from a window. At this point it no longer has a surface for drawing.

protected synchronized void onDraw (Canvas canvas)

Added in API level 1

Implement this to do your drawing.

Parameters
canvasthe canvas on which the background will be drawn

protected synchronized void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

Added in API level 1

Measure the view and its content to determine the measured width and the measured height. This method is invoked bymeasure(int, int) and should be overriden by subclasses to provide accurate and efficient measurement of their contents.

CONTRACT: When overriding this method, you must callsetMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger anIllegalStateException, thrown by measure(int, int). Calling the superclass'onMeasure(int, int) is a valid use.

The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should overrideonMeasure(int, int) to provide better measurements of their content.

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() and getSuggestedMinimumWidth()).

Parameters
widthMeasureSpechorizontal space requirements as imposed by the parent. The requirements are encoded withView.MeasureSpec.heightMeasureSpecvertical space requirements as imposed by the parent. The requirements are encoded withView.MeasureSpec.

protected void onSizeChanged(int w, int h, int oldw, int oldh)

Added in API level 1

This is called during layout when the size of this view has changed. If you were just added to the view hierarchy, you're called with the old values of 0.

Parameters
wCurrent width of this view.hCurrent height of this view.oldwOld width of this view.oldhOld height of this view.

protected void onVisibilityChanged(View changedView, int visibility)

Added in API level 8

Called when the visibility of the view or an ancestor of the view is changed.

Parameters
changedViewThe view whose visibility changed. Could be 'this' or an ancestor view.visibilityThe new visibility of changedView: VISIBLE,INVISIBLE orGONE.

protected boolean verifyDrawable(Drawable who)

Added in API level 1

If your view subclass is displaying its own Drawable objects, it should override this function and return true for any Drawable it is displaying. This allows animations for those drawables to be scheduled.

Be sure to call through to the super class when overriding this function.

Parameters
whoThe Drawable to verify. Return true if it is one you are displaying, else return the result of calling through to the super class.
Returns
  • boolean If true than the Drawable is being displayed in the view; else false and it is not allowed to animate.
0 0