Android星星评分控件SimpleRatingBar的使用
有一个项目需求,需要一个星星评分的控件,Android原生的RatingBar十分难用,而且还很丑,在网上找了很久,找到一个很好用的评分控件,在此记录和分享一下
github链接:SimpleRatingBar
1.使用方法
在Gradle文件中添加依赖
repositories {
jcenter()
}
dependencies {
compile 'com.iarcuschin:simpleratingbar:0.1.5'
}
2.可用属性和方法
设置星数:app:srb_numberOfStars/setNumberOfStars(int)
设置星数:app:srb_rating/ 设置评级setRating(float)
设置步长:app:srb_stepSize/ setStepSize(float)
设置星星大小:app:srb_starSize/ setStarSize(float)
设置最大星号:app:srb_maxStarSize/ setMaxStarSize(float)
设置边框宽度:app:srb_starsSeparation/ setStarsSeparation(float)
设置边框宽度:app:srb_starBorderWidth/ setStarBorderWidth(float)
设置星角半径:app:srb_starCornerRadius/ setStarCornerRadius(float)
设置正常状态下的星形边框颜色:app:srb_borderColor/ setBorderColor(@ColorInt int)
用正常状态设置星星填充颜色用:app:srb_fillColor/ setFillColor(@ColorInt int)
用正常状态设置星星背景颜色:app:srb_starBackgroundColor/setStarBackgroundColor(@ColorInt int)
设置正常状态下额定条的背景颜色:app:srb_backgroundColor/ setBackgroundColor(@ColorInt int)
在按下状态设置星级边框颜色:app:srb_pressedBorderColor/setPressedBorderColor(@ColorInt int)
设置星形填充颜色处于按下状态:app:srb_pressedFillColor/setPressedFillColor(@ColorInt int)
在压制状态下设置星星背景颜色:app:srb_pressedStarBackgroundColor/setPressedStarBackgroundColor(@ColorInt int)
用压力状态设置额定条的背景颜色:app:srb_pressedBackgroundColor/setPressedBackgroundColor(@ColorInt int)
启用/禁用用户的交互:app:srb_isIndicator/setIsIndicator(boolean)
启用/禁用星形边框:app:srb_drawBorderEnabled/ setDrawBorderEnabled(boolean)
设置填充方向(左或右):app:srb_gravity/ setGravity(Gravity)
得到已选中星星的个数:getRating()
得到一共有多少颗星星:getNumberOfStars()
3.简单示例
xml文件
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="评分:"
android:layout_marginRight="10dp"
android:textColor="#2f2f2f"
android:layout_gravity="center_vertical"
android:textSize="20sp"/>
<com.iarcuschin.simpleratingbar.SimpleRatingBar
android:id="@+id/ratingbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srb_starSize="40dp"
app:srb_numberOfStars="5"
app:srb_rating="3"
app:srb_stepSize="1"
app:srb_drawBorderEnabled="false"//取消边框
app:srb_starBackgroundColor="#c0c0c0"//选中前的颜色
app:srb_fillColor="@color/colorPrimary" />//选中后的颜色
</LinearLayout>
SimpleRatingBar自带点击星星变亮和滑动星星变亮的事件,不需要我们另外写代码,如果要监听选中星星个数的改变,可以添加setOnRatingBarChangeListener监听,如下:
SimpleRatingBar rating = findViewById(R.id.ratingbar);
rating.setOnRatingBarChangeListener(new SimpleRatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(SimpleRatingBar simpleRatingBar, float rating, boolean fromUser) {
//这里是防止星星的个数变成零个,最少为一个
if(rating.getRating() == 0) srating.setRating(1);
}
});