1.设置布局文件,自定义ratingbar样式
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" > <RatingBar
android:id="@+id/rb"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:numStars="5"
android:progressDrawable="@drawable/rating_star"
android:stepSize="0.5" /> <!-- 自定义ratingbar样式 --> <TextView
android:id="@+id/tv_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/rb"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:text="当前评分是:" /> <TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/rb"
android:layout_marginTop="20dp"
android:layout_toRightOf="@id/tv_num"
android:text="0.0"
android:textColor="#FF0000" /> </RelativeLayout>
2.在activity中设置监听器
package com.example.ratingbar; import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView; public class MainActivity extends Activity { private TextView tv;
private RatingBar rb; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//找到控件
tv = (TextView) findViewById(R.id.tv);
rb = (RatingBar) findViewById(R.id.rb);
rb.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {//设置ratingbar监听器 @Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
if(fromUser){//如果是用户操作
tv.setText(Float.toString(rating));//显示分数
} }
}); }
}
3.效果图