Programing

Android에서 사용자 지정 등급 표시 줄을 만드는 방법

lottogame 2020. 10. 28. 07:37
반응형

Android에서 사용자 지정 등급 표시 줄을 만드는 방법


안녕하세요, 내 응용 프로그램에서 등급을 수행하는 데 필요한 모든 것입니다 ... 그래서 사용자 지정 등급 표시 줄을 만들어야합니다 ... 누구든지이 작업을 도와 줄 수 있나요?


편집하다

모토로라 http://community.developer.motorola.com/t5/Android-App-Development-for/custom-rating-bar-style-using-android-s-ratingBar-small-style/ 에서 맞춤 등급을 확인하세요 . td-p / 10462

업데이트 됨

styles.xml

값 폴더에 있어야합니다.

 <?xml version="1.0" encoding="utf-8"?>
  <resources>
    <style name="foodRatingBar" parent="@android:style/Widget.RatingBar">
       <item name="android:progressDrawable">@drawable/food_rating_bar_full</item>
       <item name="android:minHeight">23dip</item>
       <item name="android:maxHeight">25dip</item>
   </style>
  </resources>

food_rating_bar_full.xml

이 파일은 Drawable 폴더에 있어야합니다.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/background"
    android:drawable="@drawable/food_ratingbar_full_empty" />
    <item android:id="@+id/secondaryProgress"
    android:drawable="@drawable/food_ratingbar_full_empty" />
    <item android:id="@+id/progress"
    android:drawable="@drawable/food_ratingbar_full_filled" />
</layer-list>

food_ratingbar_full_empty.xml

이 파일은 Drawable 폴더 안에 있어야합니다.

<?xml version="1.0" encoding="utf-8"?>

<!-- This is the rating bar drawable that is used to
 show a filled cookie. -->
<selector
xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"
      android:state_window_focused="true"
      android:drawable="@drawable/cookiee" />

<item android:state_focused="true"
      android:state_window_focused="true"
      android:drawable="@drawable/cookiee" />

<item android:state_selected="true"
      android:state_window_focused="true"
      android:drawable="@drawable/cookiee" />

<item android:drawable="@drawable/cookiee" />

</selector>

food_ratingbar_full_filled.xml

이 파일은 Drawable 폴더에 있어야합니다.

<?xml version="1.0" encoding="utf-8"?>

 <!-- This is the rating bar drawable that is used to
 show a unfilled cookie. -->
<selector
xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true"
      android:state_window_focused="true"
      android:drawable="@drawable/cookie" />

<item android:state_focused="true"
      android:state_window_focused="true"
      android:drawable="@drawable/cookie" />

<item android:state_selected="true"
      android:state_window_focused="true"
      android:drawable="@drawable/cookie" />

<item android:drawable="@drawable/cookie" />

</selector>

main.xml 파일은 다음과 같아야합니다.

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

    <RatingBar android:id="@+id/ratingBar1"
        style="@style/foodRatingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </RatingBar>
</LinearLayout>

MainActivity.class는 다음과 같아야합니다.

import android.app.Activity;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.Toast;

public class MainActivity extends Activity {
/** Called when the activity is first created. */

RatingBar rb;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    rb=(RatingBar)findViewById(R.id.ratingBar1);

    rb.setOnRatingBarChangeListener(new OnRatingBarChangeListener(){

        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating,
                boolean fromUser) {
            // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(),Float.toString(rating),Toast.LENGTH_LONG).show();

        }

    }); 
}
}

두 개의 이미지를 사용했습니다.

cookie.jpg

cookiee.jpg

이 두 이미지는 동일한 크기입니다. 하나는 선택한 Rating Bar를 식별하는 데 사용되고 다른 하나는 선택되지 않은 RatingBar를 식별하는 데 사용됩니다.


위의 것보다 더 쉬운 내 솔루션을 추가해야합니다. 스타일을 사용할 필요조차 없습니다.

드로어 블 폴더에 선택기 파일을 만듭니다.

custom_ratingbar_selector.xml

<?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@android:id/background"
    android:drawable="@drawable/star_off" />

 <item android:id="@android:id/secondaryProgress"
    android:drawable="@drawable/star_off" />

 <item android:id="@android:id/progress"
    android:drawable="@drawable/star_on" />

</layer-list>

레이아웃에서 선택기 파일을 progressDrawable로 설정합니다.

 <RatingBar
        android:id="@+id/ratingBar2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:progressDrawable="@drawable/custom_ratingbar_selector"
        android:numStars="8"
        android:stepSize="0.2"
        android:rating="3.0" />

그게 우리에게 필요한 전부입니다.


먼저 드로어 블에 이미지를 추가합니다.

여기에 이미지 설명 입력 여기에 이미지 설명 입력

첫 번째 사진은 "ratingbar_staroff.png"이고 두 번째 사진은 "ratingbar_staron.png"입니다.

그 후 res / drawable에 "ratingbar.xml"을 생성하십시오.

<?xml version="1.0" encoding="utf-8"?>
<!--suppress AndroidDomInspection -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+android:id/background"
        android:drawable="@drawable/ratingbar_empty" />
    <item android:id="@+android:id/secondaryProgress"
        android:drawable="@drawable/ratingbar_empty" />
    <item android:id="@+android:id/progress"
        android:drawable="@drawable/ratingbar_filled" />
</layer-list>

res / drawable에서 동일한 다음 XML

"ratingbar_empty.xml"

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true"
        android:state_window_focused="true"
        android:drawable="@drawable/ratingbar_staroff" />

    <item android:state_focused="true"
        android:state_window_focused="true"
        android:drawable="@drawable/ratingbar_staroff" />

    <item android:state_selected="true"
        android:state_window_focused="true"
        android:drawable="@drawable/ratingbar_staroff" />

    <item android:drawable="@drawable/ratingbar_staroff" />

</selector>

"ratingbar_filled"

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true"
        android:state_window_focused="true"
        android:drawable="@drawable/ratingbar_staron" />

    <item android:state_focused="true"
        android:state_window_focused="true"
        android:drawable="@drawable/ratingbar_staron" />

    <item android:state_selected="true"
        android:state_window_focused="true"
        android:drawable="@drawable/ratingbar_staron" />

    <item android:drawable="@drawable/ratingbar_staron" />

</selector>

다음으로 res / values ​​/ styles에 다음 코드 줄을 추가하십시오.

<style name="CustomRatingBar" parent="@android:style/Widget.RatingBar">
    <item name="android:progressDrawable">@drawable/ratingbar</item>
    <item name="android:minHeight">18dp</item>
    <item name="android:maxHeight">18dp</item>
</style>

이제 이미 ratingbar 리소스에 스타일을 추가 할 수 있습니다.

        <RatingBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style= "@style/CustomRatingBar"
            android:id="@+id/ratingBar"
            android:numStars="5"
            android:stepSize="0.01"
            android:isIndicator="true"/>

마지막으로 귀하의 활동에만 선언됩니다.

RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingbar);
ratingbar.setRating(3.67f);

여기에 이미지 설명 입력


훨씬 더 나은 애니메이션으로이 등급 표시 줄을 사용해 볼 수 있습니다.

스마일리

여기에 이미지 설명 입력


레이어 목록 및 선택기로 사용자 지정 등급 표시 줄을 만드는 것은 복잡하므로 RatingBar 클래스를 재정의하고 사용자 지정 RatingBar를 만드는 것이 좋습니다. createBackgroundDrawableShape ()는 빈 상태 png를 넣어야하는 함수이고 createProgressDrawableShape ()는 채워진 상태 png를 넣어야하는 함수입니다.

참고 :이 코드는 현재 svg에서 작동하지 않습니다.

public class CustomRatingBar extends RatingBar {

    @Nullable
    private Bitmap mSampleTile;

    public ShapeDrawableRatingBar(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        setProgressDrawable(createProgressDrawable());
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (mSampleTile != null) {
            final int width = mSampleTile.getWidth() * getNumStars();
            setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0), getMeasuredHeight());
        }
    }

    protected LayerDrawable createProgressDrawable() {
        final Drawable backgroundDrawable = createBackgroundDrawableShape();
        LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{
            backgroundDrawable,
            backgroundDrawable,
            createProgressDrawableShape()
        });

        layerDrawable.setId(0, android.R.id.background);
        layerDrawable.setId(1, android.R.id.secondaryProgress);
        layerDrawable.setId(2, android.R.id.progress);
        return layerDrawable;
    }

    protected Drawable createBackgroundDrawableShape() {
        final Bitmap tileBitmap = drawableToBitmap(getResources().getDrawable(R.drawable.ic_star_empty));
        if (mSampleTile == null) {
            mSampleTile = tileBitmap;
        }
        final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
        final BitmapShader bitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
        shapeDrawable.getPaint().setShader(bitmapShader);
        return shapeDrawable;
    }

    protected Drawable createProgressDrawableShape() {
        final Bitmap tileBitmap = drawableToBitmap(getResources().getDrawable(R.drawable.ic_star_full));
        final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
        final BitmapShader bitmapShader = new BitmapShader(tileBitmap, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
        shapeDrawable.getPaint().setShader(bitmapShader);
        return new ClipDrawable(shapeDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);
    }

    Shape getDrawableShape() {
        final float[] roundedCorners = new float[]{5, 5, 5, 5, 5, 5, 5, 5};
        return new RoundRectShape(roundedCorners, null, null);
    }

    public static Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }

        int width = drawable.getIntrinsicWidth();
        width = width > 0 ? width : 1;
        int height = drawable.getIntrinsicHeight();
        height = height > 0 ? height : 1;

        final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        final Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);

        return bitmap;
    }
}

개별 등급 아이콘이있는 RatingBar라는 유사한 것을 만들었습니다. 등급 아이콘에 VectorDrawables를 사용하고 있지만 모든 유형의 드로어 블을 사용할 수 있습니다.

https://github.com/manmountain/emoji-ratingbar

여기에 이미지 설명 입력


들어 SVG RatingBar 내가 사용 RatingBar 사용자 정의 벡터 드로어 블 Drawable의 중첩 과의 대답 erdomester 여기를. 이 솔루션은 SvgRatingBar레이아웃 뷰 내부의 모든 드로어 블을 탐색 하므로 RecyclerView오버 헤드가 있습니다.

SvgRatingBar.java :

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.VectorDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.graphics.drawable.shapes.Shape;
import android.os.Build;
import android.support.graphics.drawable.VectorDrawableCompat;
import android.support.v7.graphics.drawable.DrawableWrapper;
import android.support.v7.widget.AppCompatRatingBar;
import android.util.AttributeSet;
import android.view.Gravity;

public class SvgRatingBar extends AppCompatRatingBar {

    private Bitmap sampleTile;

    public SvgRatingBar(Context context) {
        this(context, null);
    }

    public SvgRatingBar(Context context, AttributeSet attrs) {
        this(context, attrs, android.support.v7.appcompat.R.attr.ratingBarStyle);
    }

    public SvgRatingBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        LayerDrawable drawable = (LayerDrawable) createTile(getProgressDrawable(), false);
        setProgressDrawable(drawable);
    }

    /**
     * Converts a drawable to a tiled version of itself. It will recursively
     * traverse layer and state list drawables.
     */
    @SuppressLint("RestrictedApi")
    private Drawable createTile(Drawable drawable, boolean clip) {
        if (drawable instanceof DrawableWrapper) {
            Drawable inner = ((DrawableWrapper) drawable).getWrappedDrawable();
            if (inner != null) {
                inner = createTile(inner, clip);
                ((DrawableWrapper) drawable).setWrappedDrawable(inner);
            }
        } else if (drawable instanceof LayerDrawable) {
            LayerDrawable background = (LayerDrawable) drawable;
            final int n = background.getNumberOfLayers();
            Drawable[] outDrawables = new Drawable[n];

            for (int i = 0; i < n; i++) {
                int id = background.getId(i);
                outDrawables[i] = createTile(background.getDrawable(i),
                        (id == android.R.id.progress || id == android.R.id.secondaryProgress));
            }
            LayerDrawable newBg = new LayerDrawable(outDrawables);

            for (int i = 0; i < n; i++) {
                newBg.setId(i, background.getId(i));
            }

            return newBg;

        } else if (drawable instanceof BitmapDrawable) {
            final BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            final Bitmap tileBitmap = bitmapDrawable.getBitmap();
            if (sampleTile == null) {
                sampleTile = tileBitmap;
            }

            final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape());
            final BitmapShader bitmapShader = new BitmapShader(tileBitmap,
                    Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
            shapeDrawable.getPaint().setShader(bitmapShader);
            shapeDrawable.getPaint().setColorFilter(bitmapDrawable.getPaint().getColorFilter());
            return (clip) ? new ClipDrawable(shapeDrawable, Gravity.START,
                    ClipDrawable.HORIZONTAL) : shapeDrawable;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && drawable instanceof VectorDrawable) {
            return createTile(getBitmapDrawableFromVectorDrawable(drawable), clip);
        } else if (drawable instanceof VectorDrawableCompat) {
            // API 19 support.
            return createTile(getBitmapDrawableFromVectorDrawable(drawable), clip);
        }
        return drawable;
    }

    private BitmapDrawable getBitmapDrawableFromVectorDrawable(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        return new BitmapDrawable(getResources(), bitmap);
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if (sampleTile != null) {
            final int width = sampleTile.getWidth() * getNumStars();
            setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0),
                    getMeasuredHeight());
        }
    }

    private Shape getDrawableShape() {
        final float[] roundedCorners = new float[]{5, 5, 5, 5, 5, 5, 5, 5};
        return new RoundRectShape(roundedCorners, null, null);
    }
}

레이아웃에서 :

<com.example.common.control.SvgRatingBar
    android:id="@+id/rate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minHeight="13dp"
    android:numStars="5"
    android:progressDrawable="@drawable/rating_bar"
    android:rating="3.5"
    android:stepSize="0.01"
    />

또한 두 개의 SVG 드로어 블을 사용하여 rating_bar.xml을 만들어야합니다.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@android:id/background"
        android:drawable="@drawable/ic_unfilled_star"
        />

    <item
        android:id="@android:id/secondaryProgress"
        android:drawable="@drawable/ic_unfilled_star"
        />

    <item
        android:id="@android:id/progress"
        android:drawable="@drawable/ic_filled_star"
        />

</layer-list>

여기에 이미지 설명 입력


나는 원래 출처를 조사
했고 여기에 내 결과가 있습니다.

styles.xml (res / values)

<!-- RatingBar -->
<style name="RatingBar" parent="@android:style/Widget.RatingBar">
    <item name="android:progressDrawable">@drawable/ratingbar_full</item>
    <item name="android:indeterminateDrawable">@drawable/ratingbar_full</item>
    <item name="android:minHeight">13.4dp</item>
    <item name="android:maxHeight">13.4dp</item>
</style>

ratingbar_full.xml (res / drawable)

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background" android:drawable="@drawable/btn_rating_star_off_normal" />
    <item android:id="@android:id/secondaryProgress" android:drawable="@drawable/btn_rating_star_off_normal" />
    <item android:id="@android:id/progress" android:drawable="@drawable/btn_rating_star_on_normal" />
</layer-list>

btn_rating_star_off_normal.png (res / drawable-xxhdpi)

여기에 이미지 설명 입력

btn_rating_star_on_normal.png (res / drawable-xxhdpi)

여기에 이미지 설명 입력

activity_ratingbar.xml (res / layout)

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

    <androidx.appcompat.widget.AppCompatRatingBar
        android:id="@+id/ratingbar"
        style="@style/RatingBar"
        android:layout_width="wrap_content"
        android:layout_height="13.4dp"
        android:isIndicator="false"
        android:numStars="5"
        android:rating="2.6"
        android:secondaryProgressTint="#00000000"
        android:stepSize="0.1" />
</FrameLayout>

이것이 결과입니다.

여기에 이미지 설명 입력

  • 등급 표시 줄의 실제 높이 (13.4dp)를 layout_height속성에 추가했습니다. 그럴 경우 wrap_content별 아래에 선이 그려 지기 때문 입니다. (제 경우에는 Android Studio 미리보기에서만)

다음 코드가 작동합니다.

@Override
protected synchronized void onDraw(Canvas canvas)
{
    int stars = getNumStars();
    float rating = getRating();
    try
    {
        bitmapWidth = getWidth() / stars;
    }
    catch (Exception e)
    {
        bitmapWidth = getWidth();
    }
    float x = 0;

    for (int i = 0; i < stars; i++)
    {
        Bitmap bitmap;
        Resources res = getResources();
        Paint paint = new Paint();

        if ((int) rating > i)
        {
            bitmap = BitmapFactory.decodeResource(res, starColor);
        }
        else
        {
            bitmap = BitmapFactory.decodeResource(res, starDefault);
        }
        Bitmap scaled = Bitmap.createScaledBitmap(bitmap, getHeight(), getHeight(), true);
        canvas.drawBitmap(scaled, x, 0, paint);
        canvas.save();
        x += bitmapWidth;
    }

    super.onDraw(canvas);
}

선택한 재료 아이콘을 사용하여 드로어 블 xml을 정의한 다음 progressDrawable 속성을 사용하여 등급 막대에 사용자 지정 드로어 블을 적용하여 사용자 지정 재료 등급 막대를 만들 수 있습니다.

등급 표시 줄 맞춤 설정에 대한 자세한 내용은 http://www.zoftino.com/android-ratingbar-and-custom-ratingbar-example을 참조 하세요.

아래 드로어 블 xml은 등급 표시 줄에 엄지 손가락 아이콘을 사용합니다.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlNormal" />
    </item>
    <item android:id="@android:id/secondaryProgress">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlActivated" />
    </item>
    <item android:id="@android:id/progress">
        <bitmap
            android:src="@drawable/thumb_up"
            android:tint="?attr/colorControlActivated" />
    </item>
</layer-list>

별이 아닌 SeekBar와 같은 트랙에서 실행되는 실선 그래디언트 선을 표시하는 사용자 지정 등급 표시 줄을 만들 때 배경 (트랙 드로어 블)의 세로 중심과 관련된 문제도 발생했습니다. 이것은 Android 개발자 및 기타 StackOverflow 항목에서 제안한 것처럼 원래 사용했던 결함이있는 드로어 블 코드 (문제를 생성 함)입니다.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@android:id/background"
        android:drawable="@drawable/seekbar_track"/>
    <item android:id="@android:id/secondaryProgress">
        <scale
            android:drawable="@drawable/seekbar_progress2"
            android:scaleWidth="100%" />
    </item>

    <item android:id="@android:id/progress" >
        <clip android:clipOrientation="horizontal" android:gravity="left" >
            <shape>
                <gradient
                    android:startColor="@color/ratingbar_bg_start"
                    android:centerColor="@color/ratingbar_bg_center"
                    android:centerX="0.5"
                    android:endColor="@color/ratingbar_bg_end"
                    android:angle="0"
                    />
            </shape>
        </clip>
    </item>    

 </layer-list>

여기서 문제는 사용자 지정 RatingBar의 배경과 관련된 첫 번째 항목입니다. 많은 항목이 썸과 트랙 사이의 수직 공간 연결이 끊어지지 않도록 layout_minHeight 기능을 큰 값으로 설정하도록 지시합니다. 이것은 나에게 해결책이 아니 었습니다. 태블릿에서 볼 때 배경은 여전히 ​​더 작은 휴대폰 기반 크기로 그려져 있었기 때문에 트랙은 RatingBar 트랙의 중앙 위에 일관되게 배치되었습니다. 해결책은 RatingBar 드로어 블에서이 항목을 제거하는 것이므로 이제 다음과 같이 보입니다.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@android:id/secondaryProgress">
        <scale
            android:drawable="@drawable/seekbar_progress2"
            android:scaleWidth="100%" />
    </item>

    <item android:id="@android:id/progress" >
        <clip android:clipOrientation="horizontal" android:gravity="left" >
            <shape>
                <gradient
                    android:startColor="@color/ratingbar_bg_start"
                    android:centerColor="@color/ratingbar_bg_center"
                    android:centerX="0.5"
                    android:endColor="@color/ratingbar_bg_end"
                    android:angle="0"
                    />
            </shape>
        </clip>
    </item>    

 </layer-list>

그런 다음 사용자 지정 RatingBar의 스타일 정의에서 layout_background를 트랙 드로어 블로 설정합니다. 내 모습은 다음과 같습니다.

<style name="styleRatingBar" parent="@android:style/Widget.RatingBar">
    <item name="android:indeterminateOnly">false</item>
    <item name="android:background">@drawable/seekbar_track</item>
    <item name="android:progressDrawable">@drawable/abratingbar</item>
    <item name="android:thumb">@drawable/abseekbar_thumb</item>
    <item name="android:minHeight">@dimen/base_29dp</item>
    <item name="android:maxHeight">@dimen/base_29dp</item>
    <item name="android:layout_marginLeft">@dimen/base_10dp</item>
    <item name="android:layout_marginRight">@dimen/base_10dp</item>
    <item name="android:layout_marginTop">@dimen/base_10dp</item>
    <item name="android:layout_marginBottom">@dimen/base_10dp</item>
    <item name="android:scaleType">fitXY</item>
</style>

(이전에는 여기서 배경 설정이 정의되지 않았습니다.)

이것은 스타일과 드로어 블을 모두 사용하는 내 레이아웃의 항목입니다.

<RatingBar
    android:id="@+id/ratingbar_vote"
    style="@style/styleRatingBar"
    android:hint="@string/ratingbar_vote"
    android:contentDescription="@string/ratingbar_vote"
    android:numStars="5"
    android:rating="5"
    android:stepSize="1"
    android:layout_width="match_parent"
    android:layout_height="@dimen/base_29dp"
    android:layout_marginLeft="@dimen/base_120dp"
    android:layout_gravity="bottom|right" />

요약하자면 사용자 지정 RatingBar 드로어 블에 배경 (트랙) 기능을 설정하지 말고 사용자 지정 RatingBar 스타일의 layout_background 기능에 설정하십시오. 이렇게하면 트랙이 항상 수평 RatingBar에서 수직으로 중앙에 위치합니다. (이 사용자 지정 RatingBar에서 등급으로 별 또는 기타 격리 된 이미지를 사용하는 대신 등급을 표시하기 위해 수평으로 "성장"하거나 "축소"하는 그라데이션 선을 사용하고 있음을 기억하십시오.이 등급 선은 SeekBar와 같은 엄지 손가락을 사용합니다. SeekBar와 같은 "트랙"에서 실행됩니다.)


이를 위해 @erdomester의 주어진 솔루션을 사용할 수 있습니다. 그러나 등급 막대 높이에 문제가있는 경우 등급 막대의 아이콘 높이를 프로그래밍 방식으로 사용할 수 있습니다.

Kotlin에서

val drawable = ContextCompat.getDrawable(context, R.drawable.rating_filled)
val drawableHeight = drawable.intrinsicHeight

rating_bar.layoutParams.height = drawableHeight

비어있는 별표로 결함이있는 이미지가있는 5 개의 이미지 뷰를 가질 수 있으며 등급에 따라 절반 또는 전체 이미지 기준으로 등급 표시 줄을 채울 수 있습니다.

 public View getView(int position, View convertView, ViewGroup parent) {
     LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     View grid=inflater.inflate(R.layout.griditem, parent, false);
     imageView=(ImageView)grid.findViewById(R.id.grid_prod);
     imageView.setImageResource(imgId[position]);
     imgoff =(ImageView)grid.findViewById(R.id.offer);
     tv=(TextView)grid.findViewById(R.id.grid_text);
     tv.setText(namesArr[position]);
     tv.setTextColor(Color.BLACK);
     tv.setPadding(0, 2, 0, 0);
   sta=(ImageView)grid.findViewById(R.id.imageView);
    sta1=(ImageView)grid.findViewById(R.id.imageView1);
    sta2=(ImageView)grid.findViewById(R.id.imageView2);
    sta3=(ImageView)grid.findViewById(R.id.imageView3);
    sta4=(ImageView)grid.findViewById(R.id.imageView4);
    Float rate=rateFArr[position];


   if(rate==5 || rate==4.5)
    {
        sta.setImageResource(R.drawable.full__small);
        sta1.setImageResource(R.drawable.full__small);
        sta2.setImageResource(R.drawable.full__small);
        sta3.setImageResource(R.drawable.full__small);
        if(rate==4.5)
        {
            sta4.setImageResource(R.drawable.half_small);
        }
        else
        {
            sta4.setImageResource(R.drawable.full__small);
        }
    }
    if(rate==4 || rate==3.5)
    {
        sta.setImageResource(R.drawable.full__small);
        sta1.setImageResource(R.drawable.full__small);
        sta2.setImageResource(R.drawable.full__small);
     if(rate==3.5)
        {
            sta3.setImageResource(R.drawable.half_small);
        }
        else
        {
            sta3.setImageResource(R.drawable.full__small);
        }
    }
    if(rate==3 || rate==2.5)
    {
        sta.setImageResource(R.drawable.full__small);
        sta1.setImageResource(R.drawable.full__small);
       if(rate==2.5)
        {
            sta2.setImageResource(R.drawable.half_small);
        }
        else
        {
            sta2.setImageResource(R.drawable.full__small);
        }
    }
    if(rate==2 || rate==1.5)
    {
    sta.setImageResource(R.drawable.full__small);
     if(rate==1.5)
        {
            sta1.setImageResource(R.drawable.half_small);
        }
        else
        {
            sta1.setImageResource(R.drawable.full__small);
        }
    }
    if(rate==1 || rate==0.5)
    {
        if(rate==1)
        sta.setImageResource(R.drawable.full__small);
        else
            sta.setImageResource(R.drawable.half_small);

    }
    if(rate>5)
    {
        sta.setImageResource(R.drawable.full__small);
        sta1.setImageResource(R.drawable.full__small);
        sta2.setImageResource(R.drawable.full__small);
        sta3.setImageResource(R.drawable.full__small);
        sta4.setImageResource(R.drawable.full__small);
    }

    // rb=(RatingBar)findViewById(R.id.grid_rating);
     //rb.setRating(rateFArr[position]);
        return grid;
    }

참고 URL : https://stackoverflow.com/questions/5800657/how-to-create-custom-ratings-bar-in-android

반응형