更改音量时更改搜索条值

时间:2017-03-01 12:40:00

标签: android volume seekbar

我有这个搜索栏,当我进入应用程序时它会获取手机音量的值(如果音量达到最大值,搜索栏已满,依此类推)。 当我更改搜索栏值时,手机的音量会发生变化(应该如此)。

但我的问题是当我通过设备中的音量增大和音量减小按钮更改手机的音量时,如何更改搜索栏的值

这是我的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    setContentView(R.layout.activity_media_player);
    initializeUIElements();
    initializeMediaPlayer();
}



 private void initializeUIElements() {

    sbPlay = (ProgressBar) findViewById(R.id.sbPlay);
    sbPlay.setMax(100);
    sbPlay.setVisibility(View.INVISIBLE);

    btPlay = (Button) findViewById(R.id.btPlay);
    btPlay.setOnClickListener(this);

    btStop = (Button) findViewById(R.id.btStop);
    btStop.setEnabled(false);
    btStop.setOnClickListener(this);

    sbVolume = (SeekBar) findViewById(R.id.sbVolume);
    try {
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        sbVolume.setMax(audioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        sbVolume.setProgress(audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC));


        sbVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
            }

            @Override
            public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                        progress, 0);
            }
        });
    }
    catch (Exception e) {
        e.printStackTrace();
    }

}

1 个答案:

答案 0 :(得分:1)

SOLVEDDD

 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
 if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) 
{ 
       int index = seekbar.getProgress(); 
       seekbar.setProgress(index + 1); 
       return true; 
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
 {
       int index = seekbar.getProgress(); 
       seekbar.setProgress(index - 1); 
       return true; 
}
 return super.onKeyDown(keyCode, event); 
}