Ratingbar UseGuide, ratingbaruseguide

Source: Internet
Author: User

Ratingbar UseGuide, ratingbaruseguide
Ratingbar UseGuide

Ratingbar is a scoring control. The system provides the following controls:

I believe everyone has seen such a control. This article will explain in detail the use and transformation of Ratingbar.

Default Ratingbar

RatingBar is an extension based on SeekBar (drag bar) and ProgressBar (status bar). It displays the rating using a star.
Let's take a look at the default Ratingbar:

The three Ratingbar types are provided by the system. The Code is as follows:

    <RatingBar        android:id="@+id/origin_ratingbar"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="8dp"        android:numStars="6"        android:rating="3"/>    <RatingBar        style="?android:attr/ratingBarStyleIndicator"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="8dp"        android:numStars="7"        android:rating="3"/>    <RatingBar        style="?android:attr/ratingBarStyleSmall"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="8dp"        android:numStars="8"        android:rating="3"/>

The first is the default Ratingbar style, which is completely original without any changes.
The second type is Ratingbar, and the system Style is used.

"? Android: attr/ratingBarStyleIndicator"

The third is the small Style Ratingbar, which uses the system Style

"? Android: attr/ratingBarStyleSmall"

The Ratingbar provided by the system can basically meet our low requirements. It provides some attributes:

Attribute Function
Android: rating = "3" Number of currently displayed stars
Android: numStars = "7" Total number of stars
Android: stepSize = "1.5" Step size when Star is added
Android: isIndicator = "true" Whether Ratingbar is available


It's easy and clear. You can see how to use it.

PS: the system's Ratingbar must use the wrap_content layout. If match_parent is used, the defined numStars will become invalid. Moreover, the system's Ratingbar cannot adjust the gap between the Star and the Star.

Custom style Ratingbar

Although the system's Ratingbar functions are met, it is too ugly to control the Star Style. Therefore, we can control the Style through the Style.

Create a Star image

First, we create a drawable:

<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android">    <item        android:id="@+android:id/background"        android:drawable="@drawable/staroff"/>    <item        android:id="@+android:id/secondaryProgress"        android:drawable="@drawable/staroff"/>    <item        android:id="@+android:id/progress"        android:drawable="@drawable/staron"/></layer-list>

It is easy to specify three attributes:

  • Progress: indicates the attribute used to fill the background image (similar to the progress bar, the first progress position)
  • SecondaryProgress: Secondary progress bar similar to progressbar
  • Background: used to fill in the background image, similar to the progress bar. When we set the maximum Star (android: numStars), the system will follow our settings, to draw the background in Star (for example, android: numStars = "5", 5 Gray stars will be drawn)

The referenced id may report an error in IDE, but does not affect compilation.

Define Style

We create a Style to define the Ratingbar Style:

    <style name="MyRatingBar" parent="@android:style/Widget.RatingBar">        <item name="android:progressDrawable">@drawable/ratingbar_bg</item>        <item name="android:minHeight">48dp</item>        <item name="android:maxHeight">48dp</item>    </style>

Expand Widget. RatingBar to customize the style, and specify its android: progressDrawable parameter as the image style we set earlier.

Reference Style

Finally, we reference the custom Style in the Code:

    <RatingBar        style="@style/MyRatingBar"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="8dp"        android:numStars="8"        android:rating="3"/>

The last display style is as follows:

There is also a pain point here, that is, once a custom Star style and background are set, Star cannot be vertically centered in the Ratingbar, you can only adjust the position based on the margin when you cut the graph, which can also solve the problem of defining the direct interval of the Star.

Override Ratingbar

This is required. In the end, we will find that the Ratingbar provided by the system is too bad to be used directly. Therefore, we will rewrite a Ratingbar.

Override Ratingbar. We will not use the system method-extend the progressbar method. We create a ViewGroup to control the displayed stars by setting different numbers of images.

Create attributes

First, we define the attrs attribute:

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="RatingBarView">        <attr name="starImageSize" format="dimension"/>        <attr name="starCount" format="integer"/>        <attr name="starEmpty" format="reference"/>        <attr name="starFill" format="reference"/>    </declare-styleable></resources>

Define four attributes to control the size, quantity, unfilled image, and filled image of the displayed Star.

Override Ratingbar

We implement this by inheriting the LinearLayout method and inserting ImageView into LinearLayout.

package com.xys.ratingbarguide;import android.content.Context;import android.content.res.TypedArray;import android.graphics.drawable.Drawable;import android.util.AttributeSet;import android.view.View;import android.view.ViewGroup;import android.view.animation.ScaleAnimation;import android.widget.ImageView;import android.widget.LinearLayout;public class RatingBarView extends LinearLayout {    public interface OnRatingListener {        void onRating(Object bindObject, int RatingScore);    }    private boolean mClickable = true;    private OnRatingListener onRatingListener;    private Object bindObject;    private float starImageSize;    private int starCount;    private Drawable starEmptyDrawable;    private Drawable starFillDrawable;    private int mStarCount;    public void setClickable(boolean clickable) {        this.mClickable = clickable;    }    public RatingBarView(Context context, AttributeSet attrs) {        super(context, attrs);        setOrientation(LinearLayout.HORIZONTAL);        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RatingBarView);        starImageSize = ta.getDimension(R.styleable.RatingBarView_starImageSize, 20);        starCount = ta.getInteger(R.styleable.RatingBarView_starCount, 5);        starEmptyDrawable = ta.getDrawable(R.styleable.RatingBarView_starEmpty);        starFillDrawable = ta.getDrawable(R.styleable.RatingBarView_starFill);        ta.recycle();        for (int i = 0; i < starCount; ++i) {            ImageView imageView = getStarImageView(context, attrs);            imageView.setOnClickListener(new OnClickListener() {                @Override                public void onClick(View v) {                    if (mClickable) {                        mStarCount = indexOfChild(v) + 1;                        setStar(mStarCount, true);                        if (onRatingListener != null) {                            onRatingListener.onRating(bindObject, mStarCount);                        }                    }                }            });            addView(imageView);        }    }    private ImageView getStarImageView(Context context, AttributeSet attrs) {        ImageView imageView = new ImageView(context);        ViewGroup.LayoutParams para = new ViewGroup.LayoutParams(Math.round(starImageSize), Math.round(starImageSize));        imageView.setLayoutParams(para);        // TODO:you can change gap between two stars use the padding        imageView.setPadding(0, 0, 40, 0);        imageView.setImageDrawable(starEmptyDrawable);        imageView.setMaxWidth(10);        imageView.setMaxHeight(10);        return imageView;    }    public void setStar(int starCount, boolean animation) {        starCount = starCount > this.starCount ? this.starCount : starCount;        starCount = starCount < 0 ? 0 : starCount;        for (int i = 0; i < starCount; ++i) {            ((ImageView) getChildAt(i)).setImageDrawable(starFillDrawable);            if (animation) {                ScaleAnimation sa = new ScaleAnimation(0, 0, 1, 1);                getChildAt(i).startAnimation(sa);            }        }        for (int i = this.starCount - 1; i >= starCount; --i) {            ((ImageView) getChildAt(i)).setImageDrawable(starEmptyDrawable);        }    }    public int getStarCount() {        return mStarCount;    }    public void setStarFillDrawable(Drawable starFillDrawable) {        this.starFillDrawable = starFillDrawable;    }    public void setStarEmptyDrawable(Drawable starEmptyDrawable) {        this.starEmptyDrawable = starEmptyDrawable;    }    public void setStarCount(int startCount) {        this.starCount = starCount;    }    public void setStarImageSize(float starImageSize) {        this.starImageSize = starImageSize;    }    public void setBindObject(Object bindObject) {        this.bindObject = bindObject;    }    public void setOnRatingListener(OnRatingListener onRatingListener) {        this.onRatingListener = onRatingListener;    }}

There is basically nothing to say about the code, and it is very simple to customize the View. We can also add an animation when displaying the Star. Here we only make a simple scaling animation. At the same time, we can solve this problem by setting the padding of the imageView.Set spacing between stars.

Finally, the display effect is as follows:

RESPONSE event

The response event of Ratingbar is similar to that of progressbar. You can set the listener to listen to the changes selected by the Star. Of course, the custom RatingbarView sets an interface to implement the listener:

RatingBar customRatingbar = (RatingBar) findViewById(R.id.origin_ratingbar);        customRatingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {            @Override            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {                Toast.makeText(MainActivity.this, String.valueOf(rating), Toast.LENGTH_SHORT).show();            }        });        RatingBarView originRatingbar = (RatingBarView) findViewById(R.id.custom_ratingbar);        originRatingbar.setOnRatingListener(new RatingBarView.OnRatingListener() {            @Override            public void onRating(Object bindObject, int RatingScore) {                Toast.makeText(MainActivity.this, String.valueOf(RatingScore), Toast.LENGTH_SHORT).show();            }        });

The parameter in the callback is the number of stars. In addition to callback, Ratingbar also provides some methods to return the number of stars.
Native:

  • MRatingBar. getMax ()
  • MRatingBar. getRating ()

Custom:

  • MRatingBarView. getStarCount ()
Library

This custom Ratingbar can be placed in a separate library project and used as a UIKit. Why am I not here? The reason is that I am relatively lazy. If you need it, just take a look. There are two files in total.

Above, Ratingbar resolution is complete, leaving only one Github:

Https://github.com/xuyisheng/RatingbarGuide

Welcome to fork and Star.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.