Android開發之RatingBar

什麼是RatingBar?

RatingBar是評分進度條。


如何使用RatingBar?

1.在佈局文件中聲明RatingBar標籤,並設置numStars屬性和stepSize屬性。

2.在Activity中創建RatingBar對象。

3.爲RatingBar對象創建監聽器類實現OnRatingBarChangeListener類,並重寫onRatingChanged()方法。

4.爲RatingBar綁定監聽器。


activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mycompany.ratingbar.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="請評分:" />
    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_below="@id/textView"
        android:numStars="5"
        android:stepSize="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>


MainActivity.java:

package com.mycompany.ratingbar;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RatingBar;

public class MainActivity extends AppCompatActivity {
    private RatingBar ratingBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ratingBar = (RatingBar) findViewById(R.id.ratingBar);

        ratingBar.setOnRatingBarChangeListener(new RatingBarListener());
    }
    
    class RatingBarListener implements RatingBar.OnRatingBarChangeListener{
        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
            System.out.println("rating------>" + rating);
        }
    }
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章