前言
此博文的五星隻能整星,并且隻是展示,比較簡單。很多時候我們項目裡可能多處用到同樣的UI展示,并且具有一定的代碼量,那麼我們可以對其做适合項目的封裝來達到減少重複代碼的工作,并且使主體業務邏輯清晰。
需求
整星評價,最低0星,最高5星

UI效果
代碼實作
xml布局檔案中:
android:id="@+id/ll_star"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/star_un" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:src="@mipmap/star_un" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:src="@mipmap/star_un" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:src="@mipmap/star_un" />
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:src="@mipmap/star_un" />
然後自定義類,在類中使用上面的xml建構view
public class FiveStarView extends LinearLayout {
private LinearLayout ll_star;
public FiveStarView(Context context) {
super(context);
init(context);
}
public FiveStarView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public FiveStarView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context){
View view = LayoutInflater.from(context).inflate(R.layout.five_star_evaluate,null);
ll_star = view.findViewById(R.id.ll_star);
this.addView(view);
}
public void setStar(int num){
if(num<=0) return;
for(int i=0;i
((ImageView)ll_star.getChildAt(i)).setImageResource(R.mipmap.star_ch);
}
}
}
代碼很簡單,對外提供了一個setStar的方法,因為控件預設布局中是灰色星星,num是0及以下(小于0屬于異常資料了)直接展示即可,num大于0小于5(大于5的資料做限制,布局中隻有五顆星)就去設定金色星就可以了。
使用
在xml布局檔案中:
android:id="@+id/star_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
在擷取到評分資訊後,直接設定就可以,比如:
star_price.setStar(1);
使用效果

最後
從使用上來看,簡單封裝以後,在項目中頻繁使用的時候是很友善的,不非得高大上,适合的就是好的。當然,也可以追求更好的。