RatingBar组件是一个打分组件,主要用于对应用打分,下面是该组件的使用示例
首先是代码:
import android.app.Activity;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.RatingBar.OnRatingBarChangeListener;
public class Main extends Activity implements OnRatingBarChangeListener
{
private RatingBar smallRatingBar;
private RatingBar indicatorRatingBar;
private TextView textView;
@Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser)
{
smallRatingBar.setRating(rating);
indicatorRatingBar.setRating(rating);
if (ratingBar.getId() == R.id.ratingbar1){
textView.setText("ratingbar1的分数:" + rating);
}else{
textView.setText("ratingbar2的分数:" + rating);
}
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//通过id获取对象
RatingBar ratingBar1 = (RatingBar) findViewById(R.id.ratingbar1);
RatingBar ratingBar2 = (RatingBar) findViewById(R.id.ratingbar2);
textView = (TextView) findViewById(R.id.textview);
//设置打分组件监听器
ratingBar1.setOnRatingBarChangeListener(this);
ratingBar2.setOnRatingBarChangeListener(this);
//通过id获取对象
smallRatingBar = (RatingBar) findViewById(R.id.smallRatingbar);
indicatorRatingBar = (RatingBar) findViewById(R.id.indicatorRatingbar);
}
}
mai.xml布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="3颗星,步长是0.5" />
<RatingBar android:id="@+id/ratingbar1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:numStars="3"
android:rating="2" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="5颗星,步长是0.1" />
<RatingBar android:id="@+id/ratingbar2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:numStars="5"
android:stepSize="0.1" />
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_marginTop="10dip">
<TextView android:id="@+id/textview" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RatingBar android:id="@+id/smallRatingbar" style="?android:attr/ratingBarStyleSmall"
android:layout_marginLeft="5dip" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<RatingBar android:id="@+id/indicatorRatingbar" style="?android:attr/ratingBarStyleIndicator"
android:layout_marginLeft="5dip" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
注:关于布局文件里几个相关属性作用:
android:numStars 打分的星数量
android:stepSize 步长设置(默认的步长是0.5)
style="?android:attr/ratingBarStyleSmall 为小星星
style="?android:attr/ratingBarStyleIndicator" 显示指示风格,不能编辑
运行结果: