我知道你们可能已经厌倦了这些帖子,但为什么当我按下音量时没有任何事情发生?我只是想制作一个简单的代码,但显然它不起作用。
package com.cakemansapps.lightwriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.FrameLayout;
import android.view.KeyEvent;
import android.util.Log;
public class LightWriter extends Activity implements OnTouchListener {
private static final String TAG = "Touch" ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
Log.w("LightWriter", "I WORK BRO.");
return true;
}
return super.onKeyLongPress(keyCode, event);
}
public boolean onTouch(View view, MotionEvent me) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
答案 0 :(得分:50)
我不知道你是否可以获得硬件密钥的长按事件。
我之前使用过此代码来收听音量按钮。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)){
//Do something
}
return true;
}
如果这对您不起作用,请告诉我们您正在测试的设备。
答案 1 :(得分:12)
另一种方法
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
答案 2 :(得分:6)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
// ... your code
return true;
} else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) {
// ... your code
return true;
} else
return super.onKeyDown(keyCode, event);
}
答案 3 :(得分:4)
试试这些。刚试过它们:
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
super.onKeyLongPress(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
Log.w("LightWriter", "I WORK BRO.");
return true;
}
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
Log.w("LightWriter", "I WORK BRO.");
return true;
}
return true;
}
答案 4 :(得分:4)
使用此代码处理音量键事件
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
super.onKeyUp(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
Toast.makeText(MainActivity.this,"Up working",Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
Toast.makeText(MainActivity.this,"Down working",Toast.LENGTH_SHORT).show();
return true;
}
return false;
}