Handle multiple button click listeners
I've two ImageButtons in my layout, "plus" and "minus". I attach a click listener to the "plus" button with a simple toast message in the click function, and it works.
ImageButton btplus = (ImageButton)findViewById(R.id.btplus);
btplus.setOnClickListener( new ImageButton.OnClickListener(){
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "+", Toast.LENGTH_SHORT);
}
});
Then i attach a second click listener to the minus ImageButton...
ImageButton btminus = (ImageButton)findViewById(R.id.btminus);
btminus.setOnClickListener( new ImageButton.OnClickListener(){
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "-", Toast.LENGTH_SHORT);
}
});
...and no more button click works! The "plus" click too stop working.
I've seen a lot of examples on this theme, but i can't see any difference between them (workin开发者_C百科g) and mine.
Such as multiple button click listners...
ImageButton btminus = (ImageButton)findViewById(R.id.btminus);
btminus.setOnClickListener(this);
ImageButton btplus = (ImageButton)findViewById(R.id.btplus);
btplus.setOnClickListener(this);
then your activity want to implements onclicklistener and you get implemented method is:
public void onClick(View v) {
switch (v.getId()) {
case R.id.btplus:
Toast.makeText(getApplicationContext(), "Plus is clicked" + "+", Toast.LENGTH_SHORT).show();
break;
case R.id.btminus:
Toast.makeText(getApplicationContext(),"Minus is clicked" + "-", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
ImageButton btplus = (ImageButton)findViewById(R.id.btplus);
btplus.setOnClickListener( new View.OnClickListener(){
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "+", Toast.LENGTH_SHORT).show();
}
});
Registered onClick event in the XML layout and then handle it in the code. This is how I would do it:
<Button
android:id="@+id/btplus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:onClick="onBtnClicked">
</Button>
Method in .class
public void onBtnClicked(View v) {
switch (v.getId()) {
case R.id.btplus:
Toast.makeText(getApplicationContext(), "Plus is clicked" + "+", Toast.LENGTH_SHORT).show();
break;
case R.id.btminus:
Toast.makeText(getApplicationContext(),"Minus is clicked" + "-", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
精彩评论