开发者

Android: onKeyUp and onKeyDown?

开发者 https://www.devze.com 2023-02-15 19:29 出处:网络
I\'m having trouble understanding onKeyUp and onKeyDown... I have an app that resembles a DialPad with imagebuttons rendered. Everytime a button is clicked a sound plays, for instance if imagebutton 0

I'm having trouble understanding onKeyUp and onKeyDown...

I have an app that resembles a DialPad with imagebuttons rendered. Everytime a button is clicked a sound plays, for instance if imagebutton 0 is clicked a sound saying "zero" will be played and during the click the imagebutton background is changed.

Here's an example of how the imagebutton works when its clicked thru the screen...

private synchronized void playSound(int tone) {
    if(mp != null) {
        mp.stop();
        mp.release();

    }
    mp = MediaPlayer.create(this.getApplicationContext(), tone);
    mp.start();
}

private void ButtonClickSound() {
    ImageButton one = (ImageButton) findViewById(R.id.btnOne);
    one.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            playSound(R.raw.mamacita_one);
        }
    });
}

Now my onKeyDown method looks like this:

    @Override
public boolean onKeyDown(int keyCode, KeyEvent ev) {

    switch (keyCode) {
    case KeyEvent.KEYCODE_0:
        playSound(R.raw.mamacita_zero);         
        return true;
    }
}

The xml for the button looks like this:

<?xml version="1.0" encoding="utf-8"?>

<item 
    android:state_pressed="true" 
    android:drawable="@drawable/green0" /> <!-- pressed -->

<item android:drawable="@drawable/blue0" /> <!-- default -->

My question is how do I implement onKeyUp and let the imagebutton switch background during the click ??开发者_如何学运维?


Use ToggleButton instead of Image Button. http://developer.android.com/reference/android/widget/ToggleButton.html

In the source code, you could use isChecked() property of ToggleButton to play sound

change the xml button to

<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/greendot"
      android:state_checked="true" />
<item android:drawable="@drawable/reddot" />
</selector>
0

精彩评论

暂无评论...
验证码 换一张
取 消