简体   繁体   中英

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?

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.

@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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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