项目结构:
1 New Android Project-> 2 Project name:SeekBar 3 Build Target:Android 2.2 4 Application name: SeekBar 5 Package name:com.b510 6 Create Activity:HelloSeekBar 7 Min SDK Version:9 8 Finish
运行效果:
代码部分:
main.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 android:orientation="vertical" 4 android:layout_width="fill_parent" 5 android:layout_height="fill_parent" 6 > 7 <TextView 8 android:layout_width="fill_parent" 9 android:layout_height="wrap_content" 10 android:text="Seek Bar Demo" 11 /> 12 <SeekBar 13 android:id="@+id/sb_test_id" 14 android:layout_width="fill_parent" 15 android:layout_height="wrap_content" 16 /> 17 </LinearLayout>
HelloSeekBar.java
1 package com.b510; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.util.Log; 6 import android.widget.SeekBar; 7 import android.widget.Toast; 8 import android.widget.SeekBar.OnSeekBarChangeListener; 9 10 public class HelloSeekBar extends Activity { 11 private static final String TAG = "HelloSeekBar"; 12 /* 申明一个SeekBar变量 */ 13 private SeekBar sb_test; 14 15 /** Called when the activity is first created. */ 16 @Override 17 public void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.main); 20 21 sb_test = (SeekBar) findViewById(R.id.sb_test_id); 22 // 进度条的最大值 23 sb_test.setMax(100); 24 sb_test.setOnSeekBarChangeListener(listener); 25 } 26 27 // 定义一个监听器,该监听器负责监听进度条状态的改变 28 private OnSeekBarChangeListener listener = new OnSeekBarChangeListener() { 29 // 当用户停止滑动滑块的时候,调用此方法 30 @Override 31 public void onStopTrackingTouch(SeekBar seekBar) { 32 Log.i(TAG, "on Stop Tracking Touch方法,当前位置: " 33 + seekBar.getProgress()); 34 Toast.makeText(HelloSeekBar.this, "onStopTrackingTouch方法", 35 Toast.LENGTH_LONG).show(); 36 } 37 38 // 当用户开始滑动滑块的时候,调用此方法 39 @Override 40 public void onStartTrackingTouch(SeekBar seekBar) { 41 Log.i(TAG, "on Start Tracking Touch方法,当前位置: " 42 + seekBar.getProgress()); 43 Toast.makeText(HelloSeekBar.this, "onStartTrackingTouch方法", 44 Toast.LENGTH_LONG).show(); 45 } 46 47 // 当进度条的进度方式变化的时候,就会调用这个方法 48 // 只要进度条的滑块发生变化,无论滑块是怎样变化的,都会调用此方法 49 @Override 50 public void onProgressChanged(SeekBar seekBar, int progress, 51 boolean fromUser) { 52 Log.i(TAG, "on Progress Changed方法,当前位置: " 53 + seekBar.getProgress()); 54 Toast.makeText(HelloSeekBar.this, "onProgressChanged方法", 55 Toast.LENGTH_LONG).show(); 56 } 57 }; 58 }