两种方法
自定义view
控件风格
自定义view
class MyView : View{
var Width1 = 0
var paint:Paint= Paint()
// var subrectwidth:Float = 0.0f
// var subrectheight:Float = 0.0f
var score = 4.0f
var bitmap1:Bitmap? = null
var bitmap2:Bitmap? = null
var bitmap3:Bitmap? = null
constructor(context: Context):super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
//初始化三张图片
init {
bitmap1 = BitmapFactory.decodeResource(context.resources, R.mipmap.evaluate_default_face)
bitmap2 = BitmapFactory.decodeResource(context.resources, R.mipmap.evaluate_yellow_face)
bitmap3 = BitmapFactory.decodeResource(context.resources, R.mipmap.evaluate_yellow_half)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
// val Height = measuredHeight
//界面宽平分5份
Width1 = measuredWidth/5
val measuredHeight = measuredHeight //界面高
if (bitmap1!!.width!=Width1){
bitmap1!!.scale(Width1,measuredHeight,true)
}
if (bitmap2!!.width!=Width1){
bitmap2!!.scale(Width1,measuredHeight,true)
}
if (bitmap3!!.width!=Width1){
bitmap3!!.scale(Width1,measuredHeight,true)
}
for (i in 0..4){
canvas!!.drawBitmap(bitmap1!!,Width1*i.toFloat(),50f,paint)
}
val a = score.toInt()
val fl = score - a
Log.e("ddd",fl.toString())
if (fl<0.5) {
for (i in 0..( a-1)) {
canvas!!.drawBitmap(bitmap2!!, Width1 * i.toFloat(), 50f, paint)
}
canvas!!.drawBitmap(bitmap3!!, Width1 * a.toFloat(), 50f, paint)
}else{
for (i in 0..a) {
canvas!!.drawBitmap(bitmap2!!, Width1 * i.toFloat(), 50f, paint)
}
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
val action = event.action
Log.e("aaa",event.x.toString())
if (event.action== MotionEvent.ACTION_DOWN){
var x = event.x
score =x/Width1+0.2f
Log.e("bbb",score.toString())
invalidate()
}
return true
}
}
控件风格
style.xml文件
<resources>
<!-- Base application theme. -->
<style name="myratingbar" parent="Widget.AppCompat.RatingBar">
<!-- Customize your theme here. -->
<item name="android:progressDrawable">@drawable/back</item>
<item name="android:minHeight">70dp</item>
<item name="android:stepSize">0.5</item>
</style>
</resources>
在 drawable内
要选用系统自带id
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 未选-->
<item
android:id="@android:id/background"
android:drawable="@drawable/evaluate_default_face"/>
<!-- 半选-->
<item
android:id="@android:id/secondaryProgress"
android:drawable="@drawable/evaluate_yellow_half"/>
<!-- 全选-->
<item
android:id="@android:id/progress"
android:drawable="@drawable/evaluate_yellow_face"/>
</layer-list>
最后在布局中加入style属性就好了,
<RatingBar
android:id="@+id/ratingbar"
android:numStars="5"
android:stepSize="0.5"
style="@style/myratingbar"
android:rating="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>