user5696067
user5696067

Reputation:

check which button is pressed

I am using Selectors to change the color of some buttons by setting the background of each button to drawable/selectors.xml.

When the button is pressed by the user the color of a button changes. But, what if I want to see which button is pressed by the user. How can I put an event to check the click on the Button by the USER.

Upvotes: 0

Views: 117

Answers (3)

pRaNaY
pRaNaY

Reputation: 25312

If your layout have multiple Button you need to try to implement View.OnClickListener to find which Button clicked.

    public class MainActivity extends AppCompactActivity implements View.OnClickListener
{
private Button button1,button2,button3;
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1=(Button)findViewById(R.id.button1);
        button2=(Button)findViewById(R.id.button2);
        button3=(Button)findViewById(R.id.button3);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
        }
        @Override
        public void onClick(View view)
        {
            switch (view.getId())
            {
                //handle multiple view click events
                case R.id.button1:
                Log.e("Which Button click","Button1 is clicked");
                break;
                case R.id.button2:
                Log.e("Which Button click","Button2 is clicked");
                break;
                case R.id.button3:
                Log.e("Which Button click","Button3 is clicked");
                break;
            }
        }
}

I hope its help you.

Upvotes: 1

JoCuTo
JoCuTo

Reputation: 2483

Yo could do something like this using isPressed() method

Button myBu= (Button) findViewById(R.id.button);
        myBu.isPressed();// example how to use it
        Log.d("is pressed?", "" + myBu.isPressed());//false, not pressed

        myBu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("is pressed", "" + v.isPressed());//true,pressed
            }
        });

Upvotes: 1

andryr
andryr

Reputation: 684

you can use a View.OnTouchListener like this :

mTouchListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent ev) {
      int action = ev.getAction();
      switch(v.getId()) {
           case R.id.button1:
              if(action==MotionEvent.ACTION_DOWN) {
                   mButtonOnePressed = true;
              }
              else if(action==MotionEvent.ACTION_UP||action==MotionEvent.ACTION_CANCEL) {
                   mButtonOnePressed = false;
              break;
           ..and so on
      }
      return false;
}
};

and for every button :

mButton1.setOnTouchListener(mTouchListener);

Upvotes: 0

Related Questions