今回はコンポーネントのレイティングバーを使用してみましょう。
レイティングバーは星のマークのインターフェイスで、何かを評価する時に星が5つので10段階(星半分も可能)で簡単に評価をつけやすい仕様が含まれています。
デフォルトでコンポーネントで用意されているのは、
1、星をタッチすると指定の星までの点灯を行ってくれる。
と言う点です。
簡単に組み込む事ができるようになっていますので、
この機会に特性と組み込み方を覚えてしまいましょう。
使い方
最初にrBarというプロジェクトを作成します。
作成が完了したら、main.xmlのファイルを開きます。
※main.xmlでは【graphical layout】で作業を行うと簡単にレイアウトの変更ができます。
TextViewクラスがデフォルトで中に配置されていると思いますが、削除をします。
次に、項目の中からrationgBarをドラッグして、main.xmlの中にいれます。
また確認の為のTextViewも追加をしておきます。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <RatingBar android:id="@+id/ratingBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" ></RatingBar> <TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" ></TextView> </LinearLayout>
特に初期設定で必要な事はありません。
ここで一度パブリッシュをしてみてください。
パブリッシュされたアプリで評価ができるのがわかるはずです。
次に、スクリプトで動作をさせてみましょう。
public RatingBar _ratingBar; public TextView _textView;
次にコンストラクタで、この変数にオブジェクトを読み込みます。
_ratingBar = (RatingBar)findViewById(R.id.ratingBar1); _textView = (TextView)findViewById(R.id.textView1);
RatingBarの移動を取得する為には、OnRatingBarChangeListenerをimplementsする必要があり、イベントをratingBarに結びつける必要があります。
またイベント実行時にonRatingChangedが実行されますが、第一引数には実行された、rationBar、第二引数には実行後の評価値(0.5刻みで、5までの10段階)第3引数にユーザーの実行による値の変更かどうかのBooleanが出力されます。
package andante.in.android.rbar; import android.app.Activity; import android.os.Bundle; import android.widget.RatingBar; import android.widget.TextView; import android.widget.RatingBar.OnRatingBarChangeListener; public class rBar extends Activity implements OnRatingBarChangeListener{ /** Called when the activity is first created. */ public RatingBar _ratingBar; public TextView _textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); _ratingBar = (RatingBar)findViewById(R.id.ratingBar1); _textView = (TextView)findViewById(R.id.textView1); _ratingBar.setOnRatingBarChangeListener(this); } public void onRatingChanged(RatingBar ratingBar , float rating,boolean fromUser){ if(fromUser){ _textView.setText(Float.toString(rating)); } } }
星の評価によってテキストの値が変更されるのがわかるはずです。