1

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?

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();
            }
        });
     }

}



Bruno
  • 3,872
  • 4
  • 20
  • 37
qazwsx
  • 11
  • 2

2 Answers2

0

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.

@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);
}
0

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

and also post your aactivity.xml file if still didnt fix

Wisdom
  • 40
  • 6
  • Yea I know its working fine, but I want to change this code to system keyboard key. – qazwsx Nov 18 '19 at 18:48
  • I don't really get your issue .....are you trying to create a keyboard layout with XML? – Wisdom Nov 19 '19 at 09:17
  • Yes, I have already keyboard, but I need to create functions for each key. I did it but on "buttons" not on "keys". – qazwsx Nov 19 '19 at 10:56