我有我的 android 评级栏,代码如下:
<RatingBar
android:id="@+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:layout_marginTop="28dp"
android:stepSize="1.0" />
我想将第一个星的值初始化为-5,这样剩下的星就会得到像-4、-3、-2...这样的值
但我不知道如何在 android 中将初始值赋予我的评级栏的第一颗星。
我想要我的评级栏具有三种颜色:
- 对于值 -5、-4、-3、-2、-1,星星颜色应为红色,
- 对于值 0 的星星颜色应该是蓝色
- 对于值 1、2、3、4、5,星形颜色应为绿色。
最佳答案
最低评分可以为0,不允许负数。
但是,您可以创建一个带有 11 颗星的评级条来表示值(-5 到 +5)
在评分栏的监听器中,将值映射到-5到+5的范围内(通过从接收到的参数中减去6)动态改变颜色如下:
- 0 : 蓝色
- 负值:红色
- 正值:绿色
因此,输出将如下所示:
Activity :
import android.app.Activity;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
public class MainActivity extends Activity {
private RatingBar ratingBar;
private TextView tvRating;
private LayerDrawable stars;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.original_activity_main);
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
tvRating = (TextView) findViewById(R.id.value);
stars = (LayerDrawable) ratingBar.getProgressDrawable();
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float ratingValue,
boolean fromUser) {
int value = (int) (ratingValue) - 6;
tvRating.setText(String.valueOf(value));
int color = Color.BLUE;
if(value > 0)
color = Color.GREEN;
else if(value < 0)
color = Color.RED;
stars.getDrawable(2).setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
}
});
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result : " />
<TextView
android:id="@+id/value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/label"
android:text="" />
<RatingBar
android:id="@+id/ratingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/label"
android:isIndicator="false"
android:numStars="11"
android:rating="0.0"
android:stepSize="1.0" />
</RelativeLayout>
关于android - 在android的评分栏中将初始值设置为第一颗星,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25738016/