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