我想在我的锻炼应用程序中实现自定义RatingBar.该栏应该有4颗星,步长为1.布局如下:
android:id="@+id/rating"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:max="4"
android:numStars="4"
android:stepSize="1"
android:scaleX="0.6"
android:scaleY="0.6"
android:layout_gravity="right" />
我想用自定义图像替换默认星星.但是每颗星都应该有不同的形象:
Star 1 =“X”表示“此项目已被禁用”
明星2 =拇指向下
明星3 =代表“中立评级”的东西
Star 4 =拇指向上
例如,当项目评级为3(中性评级)时,所有其他星形(1,2和4)应显示其图像的灰色版本.
我试图从RatingBar扩展并提出以下代码:
public class MyBar extends RatingBar {
private int[] starArrayColor = {
R.drawable.star_1_color,
R.drawable.star_2_color,
R.drawable.star_3_color,
R.drawable.star_4_color
};
private int[] starArrayGrey = {
R.drawable.star_1_grey,
R.drawable.star_2_grey,
R.drawable.star_3_grey,
R.drawable.star_4_grey
};
public MyBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public MyBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyBar(Context context) {
super(context);
}
@Override
protected synchronized void onDraw(Canvas canvas) {
int stars = getNumStars();
float rating = getRating();
for (int i=0;i
Bitmap bitmap;
Resources res = getResources();
Paint paint = new Paint();
if ((int) rating == i) {
bitmap = BitmapFactory.decodeResource(res, starArrayColor[i]);
} else {
bitmap = BitmapFactory.decodeResource(res, starArrayGrey[i]);
}
canvas.drawBitmap(bitmap, 0, 0, paint);
canvas.save();
}
super.onDraw(canvas);
}
}
可悲的是,它没有用.它使用我的自定义图像作为背景绘制正常的星星.
在这里有人知道如何帮助我解决这个问题吗?
UPDATE
感谢Gabe,我的onDraw方法现在看起来像这样:
@Override
protected synchronized void onDraw(Canvas canvas) {
int stars = getNumStars();
float rating = getRating();
float x = 0;
for (int i=0;i
Bitmap bitmap;
Resources res = getResources();
Paint paint = new Paint();
x += 50;
if ((int) rating-1 == i) {
bitmap = BitmapFactory.decodeResource(res, starArrayColor[i]);
} else {
bitmap = BitmapFactory.decodeResource(res, starArrayGrey[i]);
}
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 48, 48, true);
canvas.drawBitmap(scaled, x, 0, paint);
canvas.save();
}
}