共计 1669 个字符,预计需要花费 5 分钟才能阅读完成。
在 AndroidTV 我的项目中,应用了 RecyclerView,然而有一个问题是,当长按按键的时候,焦点容易飞的掉,故在所有的 Activity 的父类 BaseActivity 中进行按键速度管制,间接贴上代码,如下。此办法能够重点用于解决 RecyclerView 按键长按焦点飞掉乱掉的问题。
- 按键速度管制管制
- 增加了按键声音
public class BaseActivity extends FragmentActivity { | |
public AudioManager mAudioMgr = null; | |
public SoundPool sp;// 申明一个 SoundPool | |
public int keypress;// 定义一个整型用 load();来设置 suondID | |
public int translation; | |
public static final int EATKEYEVENT = 5;// 是否屏蔽按键的事件,管制按键的频率 | |
private static final int keyEventTime = 10; // 最短的按键事件应该是在 100ms | |
private static boolean eatKeyEvent = false; | |
private Handler mHandler =new Handler(){ | |
@Override | |
public void handleMessage(Message msg) {switch (msg.what) { | |
case EATKEYEVENT: | |
eatKeyEvent = false;} | |
} | |
}; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); | |
mAudioMgr = (AudioManager) getSystemService(AUDIO_SERVICE); | |
mAudioMgr.unloadSoundEffects(); | |
sp = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);// 第一个参数为同时播放数据流的最大个数,第二数据流类型,第三为声音品质 | |
keypress = sp.load(this, R.raw.keypress_standard, 1); // 把你的声音素材放到 res/raw 里,第 2 个参数即为资源文件,第 3 个为音乐的优先级 | |
translation = sp.load(this, R.raw.translation, 1); | |
} | |
@Override | |
public boolean dispatchKeyEvent(KeyEvent event) {if(event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER){return super.dispatchKeyEvent(event); | |
} | |
if (eatKeyEvent) {return true;} else {if (event.getAction() == KeyEvent.ACTION_DOWN) {sp.play(keypress, 1, 1, 0, 0, 1); | |
} | |
if (event.getRepeatCount()>=2){ | |
eatKeyEvent = true; | |
mHandler.removeMessages(EATKEYEVENT); | |
Message msg = mHandler.obtainMessage(EATKEYEVENT); | |
mHandler.sendMessageDelayed(msg, keyEventTime); | |
} | |
} | |
return super.dispatchKeyEvent(event); | |
} | |
public void playSound(){if (sp != null){sp.play(keypress, 1, 1, 0, 0, 1); | |
} | |
} | |
public void playTranslation(){if (sp != null){sp.play(translation, 1, 1, 0, 0, 1); | |
} | |
} | |
} |
正文完