cristianego
cristianego

Reputation: 81

how implement onkeydown event for custom buttons in android

I have a button defined in my layout, I implement onclick buttons without problems, but now I need to know when my button is doww and up, like onkeydown event for fisical buttons. There is something like that for customs buttons??. Because onKeyDown (int keyCode, KeyEvent event) have a int keycode but muy custom button haven't. I hope someone can take away that query. thank you in advance

Upvotes: 2

Views: 2963

Answers (2)

Shiv
Shiv

Reputation: 1267

Yes there is. try this code.

    yourButton.setOnTouchListener(new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {

               switch ( event.getAction() ) {
                case MotionEvent.ACTION_DOWN: break;
                case MotionEvent.ACTION_UP: break;
                }
                return true;
        }
    });

Upvotes: 7

Yurii Buhryn
Yurii Buhryn

Reputation: 823

I think, you can try something like this :

public class MainActivity extends Activity {

    private Button button ;
    private Boolean buttonState = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                buttonState = !buttonState;
                if(buttonState){
                    button.setText("Down");
                } else {
                    button.setText("Up");
                }               
            }
        });
    }

}

Upvotes: 0

Related Questions