안녕하세요, 내 응용 프로그램에서 등급을 수행하는 데 필요한 모든 것입니다 … 그래서 사용자 지정 등급 표시 줄을 만들어야합니다 … 누구든지이 작업을 도와 줄 수 있나요?
답변
편집하다
모토로라 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;
}
}
답변
들어 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.util.AttributeSet;
import android.view.Gravity;
import androidx.appcompat.graphics.drawable.DrawableWrapper;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
import com.example.R; // Your R.java file for R.attr.ratingBarStyle.
public class SvgRatingBar extends androidx.appcompat.widget.AppCompatRatingBar {
private Bitmap sampleTile;
public SvgRatingBar(Context context) {
this(context, null);
}
public SvgRatingBar(Context context, AttributeSet attrs) {
this(context, attrs, 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>
디자인 / 분할보기에 별 하나만 표시되는 경우 레이아웃을 새로 고칩니다.
Kotlin에서.
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.*
import android.graphics.drawable.shapes.RoundRectShape
import android.os.Build
import android.util.AttributeSet
import android.view.Gravity
import androidx.appcompat.graphics.drawable.DrawableWrapper
import androidx.appcompat.widget.AppCompatRatingBar
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat
import com.example.R; // Your R.java file for R.attr.ratingBarStyle.
class SvgRatingBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.ratingBarStyle) :
AppCompatRatingBar(context, attrs, defStyleAttr) {
private var sampleTile: Bitmap? = null
private val roundedCorners = floatArrayOf(5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f)
private val roundRectShape = RoundRectShape(roundedCorners, null, null)
init {
progressDrawable = createTile(progressDrawable, false) as LayerDrawable
}
/**
* Converts a drawable to a tiled version of itself. It will recursively
* traverse layer and state list drawables.
*/
private fun createTile(drawable: Drawable, clip: Boolean): Drawable =
when {
drawable is DrawableWrapper -> {
@SuppressLint("RestrictedApi")
var inner = drawable.wrappedDrawable
if (inner != null) {
inner = createTile(inner, clip)
@SuppressLint("RestrictedApi")
drawable.wrappedDrawable = inner
}
drawable
}
drawable is LayerDrawable -> {
val n = drawable.numberOfLayers
val outDrawables = arrayOfNulls<Drawable>(n)
for (i in 0 until n) {
val id = drawable.getId(i)
outDrawables[i] = createTile(drawable.getDrawable(i),
id == android.R.id.progress || id == android.R.id.secondaryProgress)
}
val newBg = LayerDrawable(outDrawables)
for (i in 0 until n) {
newBg.setId(i, drawable.getId(i))
}
newBg
}
drawable is BitmapDrawable -> {
val tileBitmap = drawable.bitmap
if (sampleTile == null) {
sampleTile = tileBitmap
}
val bitmapShader = BitmapShader(tileBitmap, Shader.TileMode.REPEAT,
Shader.TileMode.CLAMP)
val shapeDrawable = ShapeDrawable(roundRectShape).apply {
paint.shader = bitmapShader
paint.colorFilter = drawable.paint.colorFilter
}
if (clip) ClipDrawable(shapeDrawable, Gravity.START, ClipDrawable.HORIZONTAL)
else shapeDrawable
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && drawable is VectorDrawable -> {
createTile(getBitmapDrawableFromVectorDrawable(drawable), clip)
}
drawable is VectorDrawableCompat -> {
// Pre-Lollipop support.
createTile(getBitmapDrawableFromVectorDrawable(drawable), clip)
}
else -> drawable
}
private fun getBitmapDrawableFromVectorDrawable(drawable: Drawable): BitmapDrawable {
val bitmap = Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight,
Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return BitmapDrawable(resources, bitmap)
}
@Synchronized override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (sampleTile != null) {
val width = sampleTile!!.width * numStars
setMeasuredDimension(resolveSizeAndState(width, widthMeasureSpec, 0),
measuredHeight)
}
}
}
답변
답변
나는 원래 출처를 조사
했고 여기에 내 결과가 있습니다.
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 미리보기에서만)