• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps setOnKeyListener not working

itzjonno

Lurker
Any idea why this code doesnt work? I am trying to update a TextView of the system volume when the volume up/down key is pressed.

Code:
 TextView sysVol = (TextView)findViewById(R.id.systemVolume);        
        sysVol.setOnKeyListener(new OnKeyListener()
        {                           
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                  if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {

                    //system volume
                    int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                    int i = curVolume * 4;  
                    String aString = Integer.toString(i);   

                    TextView sysVol = (TextView)findViewById(R.id.systemVolume);
                    sysVol.setText(aString);
                    sysVol.invalidate();
                   
                    
                    return true;
                }
                    return false;
            }
        });

Racking my brain on this one, thanks guys
 
I dont know the proper commands offhand, but it looks like you are trying to se the listener on the textview. that listener will only fire if the textview has focus and I think it would need to be an EditText then (and focusable of course)

You might want to try the listener on the Activity itself.
 
I am now have this but it Overrides the functionality of up/down, is there a way to re-write it or exclude it from being overid?

Code:
@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
	    	
			  
  	    	//system volume
  	    	int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
  	        int i = curVolume;  
  	        String aString = Integer.toString(i);   
  	        
  	        TextView sysVol = (TextView)findViewById(R.id.systemVolume);
  	        sysVol.setText(aString);
  	        sysVol.invalidate();
	    	
	        return true;
	    }
	    return super.onKeyDown(keyCode, event);
	}
   
}
 
Back
Top Bottom