Android开发之自定义评分控件RatingBar

系统的RatingBar真是太难用了,各种鸡肋,无奈只有自定义View。

系统自带的RatingBar问题

  1. 无法设置star之间的距离
  2. star高度无法控制

自己写RatingBar

RatingBar用过的都知道它是一个横向展示几个星星的一个控件,有三种状态:

  • 选择了的整颗星
  • 半颗星
  • 没有选择的默认星星

既然是横向展示的一个控件,所以首先我们想到的是继承LinearLayout,即采用组合控件的形式来自定义View。取一个名字也叫RatingBar,目的就是替代系统的同名控件,代码如下:

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.LinearLayout;

public class RatingBar extends LinearLayout {
    public RatingBar(Context context) {
        this(context, null);
    }

    public RatingBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RatingBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }
}
复制代码

给RatingBar自定义属性

为了和系统的RatingBar控件的用法保持一样,我们需要参考系统的RatingBar的部分源码和属性。在工程项目/app/src/main/res/values下创建attrs.xml文件用于定义自定义View的属性,如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="RatingBar">
        <attr name="numStars" format="integer" />
        <attr name="rating" format="float" />
        <attr name="stepSize" format="float" />
        <attr name="isIndicator" format="boolean" />
    </declare-styleable>
</resources>
复制代码

可以看到这些自定义的属性名称和系统RatingBar的属性是一样的,我是直接从copy系统的。目录如下:

或者连续按下两次Shift键,弹出“Search EveryWhere”输入关键字attrs.xml也可以找到:

打开attrs.xml文件,在里面搜索关键字RatingBar即可找到系统RatingBar控件定义的属性:
自定义的RatingBar使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:isIndicator="true"
        android:numStars="8"
        android:rating="1" />

    <com.shyky.app.demo.view.RatingBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:numStars="10"
        app:rating="2" />
</LinearLayout>
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值