星级评分条(RatingBar)的功能和用法

      星级评分条与拖动条有相同的父类:AbsSeekBar,因此它们十分相似。实际上星级评分条与拖动条的用法、功能都十分接近;它们都是允许用户通过拖动条来改变进度。RatingBar与SeekBar最大区别在于;RatingBar通过星星来表示进度。

      为了让程序能响应星级评分条评分的改变,程序可以考虑为它绑定一个OnRatingBarChangeListener监听器。

      下面通过一个实例来示范RatingBar的功能和用法。

      实例:通过星级改变图片的透明度 

      该程序其实只是前一个程序的简单改变,只是将上面程序中的SeekBar组件改为使用RatingBar。下面是界面布局中关于RatingBar的代码片段。

      界面布局文件如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  >
 <ImageView android:id="@+id/image"
            android:layout_width="fill_parent"
            android:layout_height="240dp"
            android:src="@drawable/lijiang"/>
 
<!-- 定义一个星级评分条 -->
<RatingBar android:id="@+id/rating"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:numStars="5"
           android:max="255"
           android:progress="255"
           android:stepSize="0.5" />

</LinearLayout>

        上面的布局文件中指定了该星级评分条的最大值为255,当前进度为255——其中两个属性都来自于ProgressBar组件,这没有任何问题,因为RatingBar本来就是一个特殊的ProgressBar。

        主程序只要为RatingBar绑定事件监听器即可,监听星级评分条的星级改变。

package org.crazyit.helloworld;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;

public class RatingBarTest extends Activity {
    RatingBar ratingBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rating_bar_test);
        ratingBar=(RatingBar)findViewById(R.id.rating);
     final    ImageView image=(ImageView)findViewById(R.id.image);
        ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener(){

            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating,
                    boolean fromUser) {
                // TODO Auto-generated method stub
                //动态改变图片的透明度,其中255是星级评分条的最大值
                //5个星星就代表最大值255
                image.setAlpha((int)(rating*255/5));
            }
            
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.rating_bar_test, menu);
        return true;
    }

}

原文地址:https://www.cnblogs.com/wolipengbo/p/3386836.html