将硬件设备按钮连接到SeekBar

时间:2014-01-10 08:58:48

标签: android button hardware volume seekbar

如何使用用于卷的搜索栏连接硬件设备按钮? 因此,每次我点击硬件按钮以增加音量时,Seek Bar也会增加,反之亦然

public void initControls()
{
    try
    {
        volumeSeekbar = (SeekBar)findViewById(R.id.seekBar1);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        volumeSeekbar.setMax(audioManager
                .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        volumeSeekbar.setProgress(audioManager
                .getStreamVolume(AudioManager.STREAM_MUSIC));   


        volumeSeekbar.setOnSeekBarChangeListener(new 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();
    }

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

这是编辑过的代码,我得到错误类型对象未定义onKeyDown(int,keyEvent)方法。

2 个答案:

答案 0 :(得分:1)

public boolean onKeyDown(int keyCode, KeyEvent event) {
          if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) 
         { 
              mediaVlmSeekBar = (SeekBar) findViewById(R.id.seekBar1);
                int index = mediaVlmSeekBar.getProgress(); 
                mediaVlmSeekBar.setProgress(index + 1); 
                return true; 
         } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
          {
                int index = mediaVlmSeekBar.getProgress(); 
                mediaVlmSeekBar.setProgress(index - 1); 
                return true; 
         }
          return super.onKeyDown(keyCode, event); 
         }

答案 1 :(得分:0)

用这样的东西覆盖按钮输入;

public boolean onKeyDown(int keyCode, KeyEvent event) 
{ 
   if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) { 
       // Do your thing 
       return true;
   } else {
       return super.onKeyDown(keyCode, event); 
   }
}