3

ワークアウトアプリにカスタムRatingBarを実装したいと思います。バーには4つの星があり、ステップサイズは1である必要があります。レイアウトは次のようになります。

<com.example.workouttest.MyBar
    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" />

デフォルトの星をカスタム画像に置き換えたい。ただし、4つの星はそれぞれ異なる画像を持っている必要があります。

スター1=「このアイテムは無効になっています」を意味する「X」

スター2=親指を下に向ける

スター3=「中立的な評価」を表すもの

スター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<stars;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);
    }
}

悲しいことに、それは機能しませんでした。カスタム画像を背景にして、通常の星だけを描画します。

私がこの問題を解決するのを手伝う方法を知っている誰かがここにいますか?

アップデート

Gabeのおかげで、私の作業中のonDrawメソッドは次のようになりました。

@Override
protected synchronized void onDraw(Canvas canvas) {
    int stars = getNumStars();
    float rating = getRating();
    float x = 0;

    for (int i=0;i<stars;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();
    }
}
4

1 に答える 1

2

通常の星を描画するsuper.onDraw-を呼び出さないでください。そこから、他に何が機能しないのですか?

于 2013-02-14T20:46:28.060 に答える