前言
此博文的五星只能整星,并且只是展示,比较简单。很多时候我们项目里可能多处用到同样的UI展示,并且具有一定的代码量,那么我们可以对其做适合项目的封装来达到减少重复代码的工作,并且使主体业务逻辑清晰。
需求
整星评价,最低0星,最高5星
UI效果
代码实现
- xml布局文件中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/ll_star"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/star_un" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:src="@mipmap/star_un" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:src="@mipmap/star_un" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:src="@mipmap/star_un" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:src="@mipmap/star_un" />
</LinearLayout>
- 然后自定义类,在类中使用上面的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<num&&i<5;i++){
((ImageView)ll_star.getChildAt(i)).setImageResource(R.mipmap.star_ch);
}
}
}
代码很简单,对外提供了一个setStar的方法,因为控件默认布局中是灰色星星,num是0及以下(小于0属于异常数据了)直接展示即可,num大于0小于5(大于5的数据做限制,布局中只有五颗星)就去设置金色星就可以了。
- 使用
在xml布局文件中:
<com.dlihasa.view.FiveStarView
android:id="@+id/star_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
在获取到评分信息后,直接设置就可以,比如:
star_price.setStar(1);
使用效果
最后
从使用上来看,简单封装以后,在项目中频繁使用的时候是很方便的,不非得高大上,适合的就是好的。当然,也可以追求更好的。
网友评论