如何判断onClick()中单击了哪个按钮

JB_*_*ser 4 android android-widget

我在Android应用中有多个按钮.我想知道,在Java代码中,单击了哪个按钮.据我所知,这可以通过以下单一方法完成:

public void onClick(View view) {
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

在该方法中,您必须确定单击了哪个按钮.那是对的吗?

如果是这样,我怎么知道哪个被点击了?我确实有findViewById()返回的各种Button对象.我只是不知道如何使用它们来判断单击了哪个按钮.

Rag*_*dan 12

在您的活动类中实现View的OnClickListner.覆盖单击方法.

 Button b1= (Button) findViewById(R.id.button1);
//find your button id defined in your xml. 


b1.setOnClickListener(this);
// You have button OnClickListener implemented in your activity class.
//this refers to your activity context.
Run Code Online (Sandbox Code Playgroud)

我用过吐司的消息.

http://developer.android.com/guide/topics/ui/notifiers/toasts.html

 Toast.makeText(MainActivity.this,"button1", 1000).show();
 //display a toast using activity context ,text and duration
Run Code Online (Sandbox Code Playgroud)

使用开关盒,您可以检查单击了哪个按钮.

在你的onClick方法中.

switch(v.getId())  //get the id of the view clicked. (in this case button)
{
case R.id.button1 : // if its button1
    //do something
    break;
}
Run Code Online (Sandbox Code Playgroud)

这是完整的代码.

public class MainActivity extends Activity implements OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button b1= (Button) findViewById(R.id.button1);
    Button b2= (Button) findViewById(R.id.button2);
    Button b3= (Button) findViewById(R.id.button3);
    b1.setOnClickListener(this);
    b2.setOnClickListener(this);
    b3.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch(v.getId())
    {
    case R.id.button1 :
        Toast.makeText(MainActivity.this,"button1", 1000).show();
        break;
    case R.id.button2 :
        Toast.makeText(MainActivity.this,"button2", 1000).show();
        break;
    case R.id.button3 :
        Toast.makeText(MainActivity.this,"button3", 1000).show();
        break;  


    }

}
 }
Run Code Online (Sandbox Code Playgroud)


cod*_*gic 5

有不同的方法来处理这个问题。使用您目前拥有的,您可以使用

    public void onClick(View view) {
    // Do something
    view.getId();
}
Run Code Online (Sandbox Code Playgroud)

这将返回android:id您的xml. 您可以使用switch语句来比较值以决定要执行的操作并打开id. 您还可以onClick()在您xml的每个button.

<Button
    ...
    android:onClick="functionName"/>
Run Code Online (Sandbox Code Playgroud)

然后在你的java代码中你可以

public void functionName(View view) {
        // Do something
    }
Run Code Online (Sandbox Code Playgroud)

view在此点击将在button您指定这onClick在你的xml