如何知道最近在活动的所有按钮中按下了哪个按钮?

时间:2014-04-29 07:21:35

标签: android button

我的活动中有三个Buttons名为button1button2button3。在button3 onclickListener()中,我应该知道哪个最近在按钮Buttonbutton1之间按下button2

3 个答案:

答案 0 :(得分:2)

如果Button处于可重复使用View之内,ListView以下方式将对您有所帮助。  动态设置tag到每个Button,如下,

button1.setTag("button1");
button2.setTag("button2");
button3.setTag("button3");

然后在onClick方法中

@Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(), v.getTag()+" Clicked",
                    Toast.LENGTH_SHORT).show();
    }

如果Button是简单的Activity

 @Override
       public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                Toast.makeText(getApplicationContext()," Button 1 Clicked",
                            Toast.LENGTH_SHORT).show();
                break;
           case R.id.button2:
                Toast.makeText(getApplicationContext()," Button 2 Clicked",
                            Toast.LENGTH_SHORT).show();
                break;

            default:
                break;
            }

            }

答案 1 :(得分:0)

保留一个局部变量,并在按下按钮时将其设置为相应按钮的id。

int lastPressedButton;
...
@Override
public void onClick(View v) {
    lastPressedButton = v.getId();

    switch(v.getId()) {
        // normal button handling code
    }
}

答案 2 :(得分:0)

public void onClick(View v) {
switch(v.getId())
{
case R.id.b1:
                Toast.makeText(getApplicationContext()," First Button  Clicked",
                            Toast.LENGTH_SHORT).show();
                break;
case R.id.b2:
                Toast.makeText(getApplicationContext()," Second Button  Clicked",
                            Toast.LENGTH_SHORT).show();
                break;
}
}