你的位置:首页 > 操作系统

[操作系统]自定义样式RatingBar的使用


1.设置布局文件,自定义ratingbar样式

 1 <RelativeLayout ="http://schemas.android.com/apk/res/android" 2   ="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   <TextView19     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   <TextView28     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   @Override18   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       @Override27       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.效果图