RatingBar是基於SeekBar和ProgressBar的擴展,用星型來顯示等級評定。使用RatingBar的默認大小時,用戶可以觸摸/拖動或使用鍵來設置評分,它有兩種樣式(小風格用ratingBarStyleSmall,大風格用ratingBarStyleIndicator)。在工程中設置了三種樣式風格的RatingBar,並且當點擊按鈕的時候可以改變星星的級數。
效果圖:
layout文件中的xml文件:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical"
- android:background="#ff00ff">
- <TextView
- android:id="@+id/myTextView"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="當前評分:" />
- <RatingBar
- android:id="@+id/myRatingBar1"
- android:numStars="5" //設置星星的數量
- android:rating="5" //設置當前的星星級數
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:isIndicator="false"
- style="?android:attr/ratingBarStyle" //設置RatingBar的樣式
- />
- <RatingBar
- android:id="@+id/myRatingBar2"
- android:numStars="5"
- android:rating="5"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:isIndicator="false"
- style="?android:attr/ratingBarStyleIndicator"
- />
- <RatingBar
- android:id="@+id/myRatingBar3"
- android:numStars="5"
- android:rating="5"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:isIndicator="false"
- style="?android:attr/ratingBarStyleSmall"
- />
- </LinearLayout>
Activaty.java文件
- package com.cheng.ratingbarproject;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- import android.widget.RatingBar;
- import android.widget.TextView;
- import android.widget.RatingBar.OnRatingBarChangeListener;
- public class RatingBarProject extends Activity {
- //定義組件
- private RatingBar mRatingBar1;
- private RatingBar mRatingBar2;
- private RatingBar mRatingBar3;
- private TextView mTextView;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- super.setContentView(R.layout.main);
- //獲得組件
- mRatingBar1 = (RatingBar)findViewById(R.id.myRatingBar1);
- mRatingBar2 = (RatingBar)findViewById(R.id.myRatingBar2);
- mRatingBar3 = (RatingBar)findViewById(R.id.myRatingBar3);
- mTextView = (TextView)findViewById(R.id.myTextView);
- //設置RatingBar的監聽器
- OnRatingBarChangeListener orbcl = new OnRatingBarChangeListener() {
- //當點擊的時候將當前的星星級數改變爲點擊的位置的值
- @Override
- public void onRatingChanged(RatingBar ratingBar, float rating,
- boolean fromUser) {
- // TODO Auto-generated method stub
- mRatingBar2.setRating(rating);
- mRatingBar3.setRating(rating);
- mTextView.setText("當前分數:"+ rating);
- }
- };
- //綁定監聽器
- mRatingBar1.setOnRatingBarChangeListener(orbcl);
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- }
ok,今天到此了。