1.設置佈局文件,自定義ratingbar樣式 2.在activity中設置監聽器 3.效果圖 ...
1.設置佈局文件,自定義ratingbar樣式
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 tools:context="${relativePackage}.${activityClass}" > 6 7 8 <RatingBar 9 android:id="@+id/rb" 10 android:layout_width="wrap_content" 11 android:layout_height="30dp" 12 android:layout_marginLeft="20dp" 13 android:layout_marginTop="20dp" 14 android:numStars="5" 15 android:progressDrawable="@drawable/rating_star" 16 android:stepSize="0.5" /> <!-- 自定義ratingbar樣式 --> 17 18 <TextView 19 android:id="@+id/tv_num" 20 android:layout_width="wrap_content" 21 android:layout_height="wrap_content" 22 android:layout_below="@+id/rb" 23 android:layout_marginLeft="20dp" 24 android:layout_marginTop="20dp" 25 android:text="當前評分是:" /> 26 27 <TextView 28 android:id="@+id/tv" 29 android:layout_width="wrap_content" 30 android:layout_height="wrap_content" 31 android:layout_below="@+id/rb" 32 android:layout_marginTop="20dp" 33 android:layout_toRightOf="@id/tv_num" 34 android:text="0.0" 35 android:textColor="#FF0000" /> 36 37 </RelativeLayout>
2.在activity中設置監聽器
1 package com.example.ratingbar; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.view.Menu; 6 import android.view.MenuItem; 7 import android.view.View; 8 import android.widget.RatingBar; 9 import android.widget.RatingBar.OnRatingBarChangeListener; 10 import android.widget.TextView; 11 12 public class MainActivity extends Activity { 13 14 private TextView tv; 15 private RatingBar rb; 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) { 19 super.onCreate(savedInstanceState); 20 setContentView(R.layout.activity_main); 21 //找到控制項 22 tv = (TextView) findViewById(R.id.tv); 23 rb = (RatingBar) findViewById(R.id.rb); 24 rb.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {//設置ratingbar監聽器 25 26 @Override 27 public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) { 28 if(fromUser){//如果是用戶操作 29 tv.setText(Float.toString(rating));//顯示分數 30 } 31 32 } 33 }); 34 35 } 36 }
3.效果圖