效果图:
一 需求分析
我们需要实现评分的控件 那么主要有几步
1.绘制出评分控件
2.响应用户的触摸改变星星数
3.控件发生星星变化时通知监听者
二 自定义属性
需要属性:
星星总数
选中星星的图片id
空白星星的图片id
星星之间的间隔
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomRatingBar">
<attr name="pressedStar" format="reference" />
<attr name="normalStar" format="reference" />
<attr name="starNumber" format="integer" />
<attr name="starGap" format="dimension" />
</declare-styleable>
</resources>
三 创建自定义View文件 获取自定义属性 初始化各种变量
private static final String TAG = "CustomRatingBar";
private Paint starPaint;
private Bitmap starPressed, starNormal;
private int starNumberSum = 0, starGap = 0, currentPressedStarIndex = -1;
private TouchListener touchListener;
public CustomRatingBar(Context context) {
this(context, null);
}
public CustomRatingBar(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomRatingBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, context);
}
private void init(AttributeSet attrs, Context context) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CustomRatingBar);
int normalStarRes = array.getResourceId(R.styleable.CustomRatingBar_normalStar, -1);
int pressedStarRes = array.getResourceId(R.styleable.CustomRatingBar_pressedStar, -1);
starGap = (int) array.getDimension(R.styleable.CustomRatingBar_starGap, dp2px(10));
if (normalStarRes == -1 || pressedStarRes == -1) {
throw new RuntimeException("请指定资源id pressedStar normalStar! ");
}
starPressed = BitmapFactory.decodeResource(getResources(), pressedStarRes);
starNormal = BitmapFactory.decodeResource(getResources(), normalStarRes);
starNumberSum = array.getInt(R.styleable.CustomRatingBar_starNumber, 2);
starPaint = new Paint();
starPaint.setAntiAlias(true);//抗锯齿
starPaint.setDither(true);//防抖动
array.recycle();
}
private float dp2px(int dp) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}
四 测量控件
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int height = starPressed.getHeight() + getPaddingBottom() + getPaddingTop();
int width = starPressed.getWidth() * starNumberSum + starGap * (starNumberSum - 1) + getPaddingStart() + getPaddingEnd();
setMeasuredDimension(width, height);
}
五 绘制自定义控件
@Override
protected void onDraw(Canvas canvas) {
for (int i = 0; i < starNumberSum; i++) {
int startX = getPaddingStart() + (starNormal.getWidth() + starGap) * i;
int startY = getPaddingTop();
if (i <= currentPressedStarIndex) {
canvas.drawBitmap(starPressed, startX, startY, starPaint);
} else {
canvas.drawBitmap(starNormal, startX, startY, starPaint);
}
}
}
六 触摸事件
@Override
public boolean onTouchEvent(MotionEvent event) {
//Log.d(TAG, "onTouchEvent: " + event.getAction() + " event.getX() " + event.getX() + " event.getY() " + event.getY());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
//判断Y坐标落在有效区间
if (event.getY() < getPaddingTop() || event.getY() > (starNormal.getHeight() + getPaddingTop())) {
return true;
}
//判断X坐标落在有效区间
if (event.getX() < getPaddingStart() || event.getX() > (starNormal.getWidth() * starNumberSum + starGap * (starNumberSum - 1) + getPaddingStart())) {
return true;
}
//判断落在第几个星星
int starNum = (int) ((event.getX() - getPaddingStart()) / (starNormal.getWidth() + starGap));
if (currentPressedStarIndex != starNum) {
Log.d(TAG, "onTouchEvent: starNum" + starNum);
currentPressedStarIndex = starNum;
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (touchListener != null) {
touchListener.actionUp(currentPressedStarIndex);
}
break;
}
return true;//不消费事件
}
七 补充 dp转px listener增加
1.增加listener
public void setTouchListener(TouchListener touchListener) {
this.touchListener = touchListener;
}
interface TouchListener {
void actionUp(int currentStarIndex);
}
在主界面找到自定义view并且注册监听
2.内存优化 不要频繁调用invalidate 必要时才调用
3.各种单位转px:
private float dp2px(int dp) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}
八 其他代码
布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.chj.customratingbar.CustomRatingBar
android:id="@+id/customRatingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
app:normalStar="@drawable/star_normal"
app:pressedStar="@drawable/star_pressed"
app:starGap="20dp"
app:starNumber="5" />
</RelativeLayout>
主界面
public class MainActivity extends AppCompatActivity implements CustomRatingBar.TouchListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomRatingBar customRatingBar = findViewById(R.id.customRatingBar);
customRatingBar.setTouchListener(this);
}
@Override
public void actionUp(int currentStarIndex) {
Toast.makeText(this, "按下了第" + (currentStarIndex + 1) + "个星星", Toast.LENGTH_SHORT).show();
}
}
全代码
https://github.com/caihuijian/learn_darren_android.git