创build滑块来改变android的音量?

有人可以给我一个示例代码,通过滑块更改音量? 我search了很多教程,要求我创build一个全新的课程。 有更容易的方法吗?

谢谢!

Solutions Collecting From Web of "创build滑块来改变android的音量?"

添加到您的OnCreate,你必须把你的seekbar到布局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); } }); 

特拉维斯在新波士顿有一个伟大的video教程在这里: http : //www.youtube.com/watch?v=8sr2Y6Aff6Y

教程的源代码可以在这里find: http : //www.mybringback.com/bringers/android/thenewboston-android-series/828/thenewboston-sample-projects/

六年后,这个稍微改变的版本适用于Android Studio 3.1。 IDE说我必须声明AudioManager最后:

  /* 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