次にコンポーネントのシークバーを使用してみましょう。
シークバーは、ある程度あいまいな数値を決定する時にユーザーが簡単に値を決めれるようなコンポーネントです。
デフォルトでコンポーネントで用意されているのは、
1、つまみがつかめる。
と言う点です。
簡単に組み込む事ができるようになっていますので、
この機会に特性と組み込み方を覚えてしまいましょう。
使い方
最初にsBarというプロジェクトを作成します。
作成が完了したら、main.xmlのファイルを開きます。
※main.xmlでは【graphical layout】で作業を行うと簡単にレイアウトの変更ができます。
TextViewクラスがデフォルトで中に配置されていると思いますが、削除をします。
次に、項目の中からseekBarをドラッグして、main.xmlの中にいれます。
特に必要はないのですが、見やすくなる為にmarginで左と上と右に5spづつ隙間をあけてあげます。
また確認の為の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" > <SeekBar android:layout_height="wrap_content" android:id="@+id/seekBar1" android:layout_width="fill_parent" android:layout_marginLeft="5sp" android:layout_marginRight="5sp" android:layout_marginTop="5sp" ></SeekBar> <TextView android:layout_height="wrap_content" android:id="@+id/textView1" android:text="TextView" android:layout_width="wrap_content" ></TextView> </LinearLayout>
marginの値の設定に関しては、プロパティでも直接入力でも問題ありません。
ここで一度パブリッシュをしてみてください。
パブリッシュされたアプリでseekbarの移動ができるのがわかるはずです。
次に、スクリプトで動作をさせてみましょう。
private SeekBar _seekBar; private TextView _textView;
次にコンストラクタで、この変数にオブジェクトを読み込みます。
_seekBar = (SeekBar)findViewById(R.id.seekBar1); _textView = (TextView)findViewById(R.id.textView1);
seekBarの移動を取得する為には、OnSeekBarChangeListenerをimplementsする必要があり、イベントをseekBarに結びつける必要があります。
また、イベントの取得に際してはイベントの動いてる最中と最初と最後の3つのfunctionを用意する必要があります。(使わなかったとしてもです。)onProgressChangedとonStartTrackingTouchとonStopTrackingTouchです。
また、進捗はユーザーからの操作かどうか?と言うfromUserと言う判定を使用していますが、これはもし、他のコンポーネントなどと同時に利用をした時に、コンポーネントの動作に同期しあってこのコンポーネントと動作をする場合に、お互いの動作が無限に続いてしまう事をさける為に利用します。(今回は特い必要ありませんが。)
package andante.in.android.sbar; import android.app.Activity; import android.os.Bundle; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class sBar extends Activity implements OnSeekBarChangeListener{ /** Called when the activity is first created. */ private SeekBar _seekBar; private TextView _textView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); _seekBar = (SeekBar)findViewById(R.id.seekBar1); _textView = (TextView)findViewById(R.id.textView1); _seekBar.setOnSeekBarChangeListener(this); } public void onProgressChanged(SeekBar seekBar,int progress,boolean fromUser){ if(fromUser){ _textView.setText(Integer.toString(progress)); } } public void onStartTrackingTouch(SeekBar seek){ } public void onStopTrackingTouch(SeekBar seekBar){ } }
シークバーを動かすと、数値が動的に変化すると思います。