SeekBar可以通过滑块的位置来标识数值----而且拖动条允许用户拖动滑块来改变值,因此拖动条通常用于对系统的某种数值进行调节,比如调节音量等。
SeekBar允许用户改变拖动条的滑块外观,改变滑块外观通常通过如下属性来指定: android:thumb: 指定一个Drawable对象,该对象将自定义滑块。
为了让程序能响应拖动条滑块位置的改变,程序可以考虑为它绑定一个OnSeekBarChangeListener监听器。
以下是一个使用SeekBar来调节系统音量的实例:
XML代码:
//滑块样式
seekbar_style.xml:
-
-
thumb.xml:
bacon_seekbar.xml:
JAVA代码:
public class PianoActivity extends Activity {
/** Called when the activity is first created. */
private ImageButton imageButton_white1;
private MediaPlayer mediaPlayer01;
public AudioManager audiomanage;
private TextView mVolume ; //显示当前音量
public SeekBar soundBar;
private int maxVolume, currentVolume;
private int volume=0; //初始化声音
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mediaPlayer01 = new MediaPlayer();
imageButton_white1=(ImageButton)findViewById(R.id.white1);
final SeekBar soundBar=(SeekBar)findViewById(R.id.sound); //音量设置
mVolume = (TextView)findViewById(R.id.mVolume);
audiomanage = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
maxVolume = audiomanage.getStreamMaxVolume(AudioManager.STREAM_MUSIC); //获取系统最大音量
soundBar.setMax(maxVolume); //拖动条最高值与系统最大声匹配
currentVolume = audiomanage.getStreamVolume(AudioManager.STREAM_MUSIC); //获取当前值
soundBar.setProgress(currentVolume);
mVolume.setText(currentVolume*100/maxVolume + " %");
soundBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() //调音监听器
{
public void onProgressChanged(SeekBar arg0,int progress,boolean fromUser)
{
audiomanage.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
currentVolume = audiomanage.getStreamVolume(AudioManager.STREAM_MUSIC); //获取当前值
soundBar.setProgress(currentVolume);
mVolume.setText(currentVolume*100/maxVolume + " %");
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
TextView的XML没有给出,需要自己添加。