RatingBar.java revision 08c7116ab9cd04ad6dd3c04aa1017237e7f409ac
1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.widget; 18 19import android.content.Context; 20import android.content.res.TypedArray; 21import android.graphics.drawable.shapes.RectShape; 22import android.graphics.drawable.shapes.Shape; 23import android.util.AttributeSet; 24import com.android.internal.R; 25 26/** 27 * A RatingBar is an extension of SeekBar and ProgressBar that shows a rating in 28 * stars. The user can touch/drag or use arrow keys to set the rating when using 29 * the default size RatingBar. The smaller RatingBar style ( 30 * {@link android.R.attr#ratingBarStyleSmall}) and the larger indicator-only 31 * style ({@link android.R.attr#ratingBarStyleIndicator}) do not support user 32 * interaction and should only be used as indicators. 33 * <p> 34 * When using a RatingBar that supports user interaction, placing widgets to the 35 * left or right of the RatingBar is discouraged. 36 * <p> 37 * The number of stars set (via {@link #setNumStars(int)} or in an XML layout) 38 * will be shown when the layout width is set to wrap content (if another layout 39 * width is set, the results may be unpredictable). 40 * <p> 41 * The secondary progress should not be modified by the client as it is used 42 * internally as the background for a fractionally filled star. 43 * 44 * @attr ref android.R.styleable#RatingBar_numStars 45 * @attr ref android.R.styleable#RatingBar_rating 46 * @attr ref android.R.styleable#RatingBar_stepSize 47 * @attr ref android.R.styleable#RatingBar_isIndicator 48 */ 49public class RatingBar extends AbsSeekBar { 50 51 /** 52 * A callback that notifies clients when the rating has been changed. This 53 * includes changes that were initiated by the user through a touch gesture 54 * or arrow key/trackball as well as changes that were initiated 55 * programmatically. 56 */ 57 public interface OnRatingBarChangeListener { 58 59 /** 60 * Notification that the rating has changed. Clients can use the 61 * fromUser parameter to distinguish user-initiated changes from those 62 * that occurred programmatically. This will not be called continuously 63 * while the user is dragging, only when the user finalizes a rating by 64 * lifting the touch. 65 * 66 * @param ratingBar The RatingBar whose rating has changed. 67 * @param rating The current rating. This will be in the range 68 * 0..numStars. 69 * @param fromUser True if the rating change was initiated by a user's 70 * touch gesture or arrow key/horizontal trackbell movement. 71 */ 72 void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser); 73 74 } 75 76 private int mNumStars = 5; 77 78 private int mProgressOnStartTracking; 79 80 private OnRatingBarChangeListener mOnRatingBarChangeListener; 81 82 public RatingBar(Context context, AttributeSet attrs, int defStyleAttr) { 83 this(context, attrs, defStyleAttr, 0); 84 } 85 86 public RatingBar(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { 87 super(context, attrs, defStyleAttr, defStyleRes); 88 89 final TypedArray a = context.obtainStyledAttributes( 90 attrs, R.styleable.RatingBar, defStyleAttr, defStyleRes); 91 final int numStars = a.getInt(R.styleable.RatingBar_numStars, mNumStars); 92 setIsIndicator(a.getBoolean(R.styleable.RatingBar_isIndicator, !mIsUserSeekable)); 93 final float rating = a.getFloat(R.styleable.RatingBar_rating, -1); 94 final float stepSize = a.getFloat(R.styleable.RatingBar_stepSize, -1); 95 a.recycle(); 96 97 if (numStars > 0 && numStars != mNumStars) { 98 setNumStars(numStars); 99 } 100 101 if (stepSize >= 0) { 102 setStepSize(stepSize); 103 } else { 104 setStepSize(0.5f); 105 } 106 107 if (rating >= 0) { 108 setRating(rating); 109 } 110 111 // A touch inside a star fill up to that fractional area (slightly more 112 // than 1 so boundaries round up). 113 mTouchProgressOffset = 1.1f; 114 } 115 116 public RatingBar(Context context, AttributeSet attrs) { 117 this(context, attrs, com.android.internal.R.attr.ratingBarStyle); 118 } 119 120 public RatingBar(Context context) { 121 this(context, null); 122 } 123 124 /** 125 * Sets the listener to be called when the rating changes. 126 * 127 * @param listener The listener. 128 */ 129 public void setOnRatingBarChangeListener(OnRatingBarChangeListener listener) { 130 mOnRatingBarChangeListener = listener; 131 } 132 133 /** 134 * @return The listener (may be null) that is listening for rating change 135 * events. 136 */ 137 public OnRatingBarChangeListener getOnRatingBarChangeListener() { 138 return mOnRatingBarChangeListener; 139 } 140 141 /** 142 * Whether this rating bar should only be an indicator (thus non-changeable 143 * by the user). 144 * 145 * @param isIndicator Whether it should be an indicator. 146 * 147 * @attr ref android.R.styleable#RatingBar_isIndicator 148 */ 149 public void setIsIndicator(boolean isIndicator) { 150 mIsUserSeekable = !isIndicator; 151 setFocusable(!isIndicator); 152 } 153 154 /** 155 * @return Whether this rating bar is only an indicator. 156 * 157 * @attr ref android.R.styleable#RatingBar_isIndicator 158 */ 159 public boolean isIndicator() { 160 return !mIsUserSeekable; 161 } 162 163 /** 164 * Sets the number of stars to show. In order for these to be shown 165 * properly, it is recommended the layout width of this widget be wrap 166 * content. 167 * 168 * @param numStars The number of stars. 169 */ 170 public void setNumStars(final int numStars) { 171 if (numStars <= 0) { 172 return; 173 } 174 175 mNumStars = numStars; 176 177 // This causes the width to change, so re-layout 178 requestLayout(); 179 } 180 181 /** 182 * Returns the number of stars shown. 183 * @return The number of stars shown. 184 */ 185 public int getNumStars() { 186 return mNumStars; 187 } 188 189 /** 190 * Sets the rating (the number of stars filled). 191 * 192 * @param rating The rating to set. 193 */ 194 public void setRating(float rating) { 195 setProgress(Math.round(rating * getProgressPerStar())); 196 } 197 198 /** 199 * Gets the current rating (number of stars filled). 200 * 201 * @return The current rating. 202 */ 203 public float getRating() { 204 return getProgress() / getProgressPerStar(); 205 } 206 207 /** 208 * Sets the step size (granularity) of this rating bar. 209 * 210 * @param stepSize The step size of this rating bar. For example, if 211 * half-star granularity is wanted, this would be 0.5. 212 */ 213 public void setStepSize(float stepSize) { 214 if (stepSize <= 0) { 215 return; 216 } 217 218 final float newMax = mNumStars / stepSize; 219 final int newProgress = (int) (newMax / getMax() * getProgress()); 220 setMax((int) newMax); 221 setProgress(newProgress); 222 } 223 224 /** 225 * Gets the step size of this rating bar. 226 * 227 * @return The step size. 228 */ 229 public float getStepSize() { 230 return (float) getNumStars() / getMax(); 231 } 232 233 /** 234 * @return The amount of progress that fits into a star 235 */ 236 private float getProgressPerStar() { 237 if (mNumStars > 0) { 238 return 1f * getMax() / mNumStars; 239 } else { 240 return 1; 241 } 242 } 243 244 @Override 245 Shape getDrawableShape() { 246 // TODO: Once ProgressBar's TODOs are fixed, this won't be needed 247 return new RectShape(); 248 } 249 250 @Override 251 void onProgressRefresh(float scale, boolean fromUser, int progress) { 252 super.onProgressRefresh(scale, fromUser, progress); 253 254 // Keep secondary progress in sync with primary 255 updateSecondaryProgress(progress); 256 257 if (!fromUser) { 258 // Callback for non-user rating changes 259 dispatchRatingChange(false); 260 } 261 } 262 263 /** 264 * The secondary progress is used to differentiate the background of a 265 * partially filled star. This method keeps the secondary progress in sync 266 * with the progress. 267 * 268 * @param progress The primary progress level. 269 */ 270 private void updateSecondaryProgress(int progress) { 271 final float ratio = getProgressPerStar(); 272 if (ratio > 0) { 273 final float progressInStars = progress / ratio; 274 final int secondaryProgress = (int) (Math.ceil(progressInStars) * ratio); 275 setSecondaryProgress(secondaryProgress); 276 } 277 } 278 279 @Override 280 protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 281 super.onMeasure(widthMeasureSpec, heightMeasureSpec); 282 283 if (mSampleTile != null) { 284 // TODO: Once ProgressBar's TODOs are gone, this can be done more 285 // cleanly than mSampleTile 286 final int width = mSampleTile.getWidth() * mNumStars; 287 setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0), 288 getMeasuredHeight()); 289 } 290 } 291 292 @Override 293 void onStartTrackingTouch() { 294 mProgressOnStartTracking = getProgress(); 295 296 super.onStartTrackingTouch(); 297 } 298 299 @Override 300 void onStopTrackingTouch() { 301 super.onStopTrackingTouch(); 302 303 if (getProgress() != mProgressOnStartTracking) { 304 dispatchRatingChange(true); 305 } 306 } 307 308 @Override 309 void onKeyChange() { 310 super.onKeyChange(); 311 dispatchRatingChange(true); 312 } 313 314 void dispatchRatingChange(boolean fromUser) { 315 if (mOnRatingBarChangeListener != null) { 316 mOnRatingBarChangeListener.onRatingChanged(this, getRating(), 317 fromUser); 318 } 319 } 320 321 @Override 322 public synchronized void setMax(int max) { 323 // Disallow max progress = 0 324 if (max <= 0) { 325 return; 326 } 327 328 super.setMax(max); 329 } 330 331 @Override 332 public CharSequence getAccessibilityClassName() { 333 return RatingBar.class.getName(); 334 } 335} 336