android 评分设置显示小星星

2017-05-16  本文已影响257人  毹毹

在android中经常会遇到评分这中情况,如下图所示

网络来源

当然android中本身就可以实现---RatingBar控件

<RatingBar

android:id="@+id/ratingBar"

android:numStars="5" //总级别,总分,星星个数

android:rating="1.5"  //当前级别,分数,星星个数

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

大多时候你并不想用android原生的组件,并不是你觉得他太low,而是往往有一定局限,无法实现你想要的效果,这时候就自己定制一款吧!

我想要实现由自己的图来实现评分的星星数量和颜色。

如下图

网络来源

我有五颗星星作为评价(不可点,只是显示状态)

下面来具体实现下:

1、自定义View----GradeStarView

GradeStarView继承LinearLayout

private Context mContext;    private int[] mImages;    private int number = 5;    private ListmImgGradeStars;

public GradeStarView(Context context) {

//        super(context);

this(context, null);

}

public GradeStarView(Context context, AttributeSet attrs) {

super(context, attrs);

this.mContext = context;

this.setOrientation(LinearLayout.HORIZONTAL);

mImages = new int[]{R.drawable.ic_xx,

R.drawable._xx, R.drawable.ic_xx,

R.drawable.ic_xx, R.drawable.ic_xx,

R.drawable.ic_xx_no};

mImgGradeStars = new ArrayList();

LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT,

LayoutParams.WRAP_CONTENT);

layoutParams.leftMargin = 2;

layoutParams.rightMargin = 2;

for (int i = 0; i < number; i++) {

ImageView imageView = new ImageView(mContext);

mImgGradeStars.add(imageView);

this.addView(imageView, layoutParams);

}

}

//设置显示星星的方法

public voidsetRating(intrating) {

intratingCount = rating /2;

intratingHalf = ((rating %2) *5) %10;

for(int i=0;i<number;i++){

finalImageViewratingImage =mImgGradeStars.get(i);

if(i <= (ratingCount-1)) {

ratingImage.setImageResource(mImages[0]);

}else if(i ==ratingCount) {

if(ratingHalf>0&&ratingHalf<=5) {

ratingImage.setImageResource(mImages[mImages.length-2]);

}else if(ratingHalf >5&& ratingHalf <=9) {

ratingImage.setImageResource(mImages[0]);

}else if(ratingHalf ==0) {

ratingImage.setImageResource(mImages[mImages.length-1]);

}

} else {

ratingImage.setImageResource(mImages[mImages.length - 1]);

}

}

}

调用的时候:

gradeStarView= (GradeStarView) findViewById(R.id.grade_StarView);

gradeStarView.setRating(Integer.parseInt(star));

上一篇下一篇

猜你喜欢

热点阅读