android中的RatingBar是星級評分條,相似於淘寶中購物後給予買家的星級評分。java
該實例是經過點擊評分條,會彈出一個信息框,提示所打分數,監聽評分條事件能夠經過setOnRatingBarChangeListener()方法實現。android
首先是佈局文件:app
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="main.test_ratingbar.MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:text="@string/tv1" /> <RatingBar android:id="@+id/ratingBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#ff0"/> <!-- background呈現黃色 --> </LinearLayout>
其次是strings.xml文件:ide
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Test_RatingBar</string> <string name="tv1">請打分:</string> </resources>
再次是android源碼文件:佈局
package main.test_ratingbar; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.RatingBar; import android.widget.RatingBar.OnRatingBarChangeListener; import android.widget.Toast; public class MainActivity extends ActionBarActivity implements OnRatingBarChangeListener{ private RatingBar ratingBar=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ratingBar=(RatingBar) findViewById(R.id.ratingBar1); ratingBar.setOnRatingBarChangeListener(MainActivity.this); } @Override public void onRatingChanged(RatingBar arg0, float arg1, boolean arg2) {//第二個參數是點擊時返回的評分值 Toast.makeText(MainActivity.this, "您打出的分數是:"+arg1, Toast.LENGTH_LONG).show(); } }
最後是測試結果:測試