Android: Help creating a button that produces the same result as hitting the down key on the D-Pad? (part 2)

怎甘沉沦 提交于 2019-12-24 10:31:57

问题


Why doesn't this work?? I am trying to create an onClickListener for a button that produces the same effect as pressing the "down" key on the D-pad. Eclipse gives me an error, saying: "Cannot make a static reference to the non-static method sendDownUpKeyEvents(int) from the type InputMethodService" Help!

downButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {

                InputMethodService.sendDownUpKeyEvents(0x00000014);
            }

回答1:


You're trying to invoke non-static method in a static way. You need to obtain an instance of the service first and then invoke the method on the instance. Also the way you're doing the simulation of keypress looks incorrect. UPD: After some digging I've managed to simulate key event, try:

new Thread(new Runnable() {         
    @Override
    public void run() {                 
        new Instrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
    }   
}).start();



回答2:


Same solution, just will take a parameter.

private void InjectKeys(final int keyEventCode) {
 new Thread(new Runnable() {
  @Override
  public void run() {
   new Instrumentation().sendKeyDownUpSync(keyEventCode);
  }
 }).start();
}

Just call and pass the KeyEvent.KEYCODE like so InjectKeys(KeyEvent.KEYCODE_DPAD_DOWN);

Please don't downvote or upvote me, my answer is exactly like the above answer, I just modified it to use parameters.



来源:https://stackoverflow.com/questions/3526339/android-help-creating-a-button-that-produces-the-same-result-as-hitting-the-dow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!