简体   繁体   English

如何在视图中添加按键点击事件?

[英]How to add key click event in on view?

How can I do key event.我该如何做关键事件。 I do it, but on button event.我这样做了,但是在按钮事件上。 I have to change it to key.我必须将其更改为密钥。 I have my keyboard from How can you make a custom keyboard in Android?我的键盘来自How can you make a custom keyboard in Android?

My buttons events:我的按钮事件:

public class MainActivity extends AppCompatActivity {

    private static final int pic_id = 123;
    EditText editText;
    Button button1;
    Button button2;
    Button button3;
    Button button5;
    Button button6; 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.editText);
        button1 = (Button) findViewById(R.id.n1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.setText("I am custom Keyboard!");
            }
        });
        final MediaPlayer sawSound = MediaPlayer.create(this, R.raw.playagame);
        button2 = (Button) this.findViewById(R.id.playMusic);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sawSound.start();
            }
        });
     }

}



I don't know whether I got you right: do you mean whether reacting to key events of a physical keyboard?我不知道我是否正确:您的意思是是否对物理键盘的按键事件做出反应? If so, you should be able to overwrite dispatchKeyEvent of your keyboard activity.如果是这样,您应该能够覆盖键盘活动的dispatchKeyEvent

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_UP) {
        switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_2:
            case KeyEvent.KEYCODE_NUMPAD_2:
                handleInput("2");
                return true;
        }
    }

    return super.dispatchKeyEvent(event);
}

Your code seems to be working fine.....it plays the music check your xml file and cross-check if you are reffering the correct id to each button and check your device volume sound incase its muted您的代码似乎工作正常.....它播放音乐检查您的 xml 文件并交叉检查您是否为每个按钮提供正确的 id 并检查您的设备音量声音以防静音

and also post your aactivity.xml file if still didnt fix如果仍然没有修复,还发布您的 aactivity.xml 文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM