有人可以给我一个通过滑块改变音量的示例代码吗? 我搜索过,很多教程都要求我创建一个全新的课程。有更简单的方法吗?
谢谢!
答案 0 :(得分:19)
将此添加到OnCreate,您必须将搜索栏放入布局xml文件中:
audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
SeekBar volControl = (SeekBar)findViewById(R.id.volbar);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar arg0) {
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
}
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
}
});
答案 1 :(得分:1)
新波士顿的特拉维斯在这里有一个很棒的视频教程: http://www.youtube.com/watch?v=8sr2Y6Aff6Y
教程的源代码可以在这里找到:http://www.mybringback.com/bringers/android/thenewboston-android-series/828/thenewboston-sample-projects/
答案 2 :(得分:0)
六年后,这个略有改动的版本适用于Android Studio 3.1。 IDE说我必须声明AudioManager final:
/* volume slider*/
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
SeekBar volControl = (SeekBar)findViewById(R.id.volControl);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar arg0) {
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
}
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
}
});
//end Volume slider