Search code examples
androidbuttonclick

Android Onclick


How are you? I am new at Android programming. so far I have run a single app on my mobile phone using 4.1 API 16. My question is when releasing a click event the button image in the following code should be restored to previous state.

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        x = x + 1;
        edittext.setText("" + x);
        button.setBackgroundResource(R.drawable.buttonpressed1);
    }
});

Solution

  • There is a full solution for you:

    ImageButton guessButton;
    
    guessButton = (ImageButton) findViewById(R.id.Knorr_Game_Guess_Button);
            guessButton.setOnTouchListener(new View.OnTouchListener()
            {
                @Override
                public boolean onTouch(View v, MotionEvent event) 
               {
                    if (event.getAction() == MotionEvent.ACTION_DOWN)
                    {
                        v.setBackgroundResource(R.drawable.ic_picture1);
                    } 
                    else if (event.getAction() == MotionEvent.ACTION_UP) 
                    {
                        v.setBackgroundResource(R.drawable.ic_picture2);
                    }
                    return false;
                }
            });
    

    It works:)