自定义 rating bar,拿去就能用。

2018-06-20  本文已影响0人  黄小楼vincent

由于项目需要一个评分控件,搜了一下网上的。代码太多。功能太强大,使用太麻烦,索性就自己写了一个。

也由于实在是懒,所以,就不自定义属性了。先能用就行。等哪天心情好了再把它优化好吧。

public class RatingStart extends LinearLayout {
private int startIconResId;
private int padding = 20;
private int numStars = 5;
private ImageView[] imageViews;

private int currentSelectedIndex = -1;


public RatingStart(Context context) {
    super(context);
    init();
}

public RatingStart(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    init();
}

private void init() {
    this.setOrientation(LinearLayout.HORIZONTAL);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
}

public void build() {
    this.removeAllViews();
    imageViews = new ImageView[numStars];
    for (int i = 0; i < numStars; i++) {
        ImageView imageView = new ImageView(this.getContext());
        imageView.setImageResource(startIconResId);
        imageView.setPadding(padding , 0, padding , 0);
        addView(imageView);
        imageViews[i] = imageView;
        imageView.setOnClickListener(new ImageClickListener(i));
    }
}

private class ImageClickListener implements View.OnClickListener {
    private int index;

    public ImageClickListener(int index) {
        this.index = index;
    }

    @Override
    public void onClick(View v) {
        currentSelectedIndex = index;
        for (int i = 0; i < imageViews.length; i++) {
            imageViews[i].setSelected(i <= index);
        }
    }
}

public void setStartIconResId(int startIconResId) {
    this.startIconResId = startIconResId;
}

public void setPadding(int padding) {
    this.padding = padding;
}

public void setNumStars(int numStars) {
    this.numStars = numStars;
}

public int getCurrentSelectedIndex() {
    return currentSelectedIndex;
}

}

然后在需要的XML 里面

<com.ls.testsdk.widget.RatingStart
android:id="@+id/radtingStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

最后在activity
radtingStart.setPadding(20);
radtingStart.setNumStars(5);
radtingStart.setStartIconResId(R.drawable.service_evaluating_start_bg);
radtingStart.build();

上一篇下一篇

猜你喜欢

热点阅读