Significance of using ID in switch statements in onClick() - java

I wanted to ask what was the significance of creating a switch statement when implementing the onClickListener interface for multiple buttons. Like, we're already calling the setOnClickListener for that particular button by saying button_name.setOnClickListener()
So what's the point of specifying the id's again in the switch statement ? Why is it necessary to do so ? doesn't the point of doing button_name.setOnClickListener() mean - "do what's in here for this button" ?
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
// So we will make
switch (v.getId() /*to get clicked view id**/) {
case R.id.corky:
// do something when the corky is clicked
break;
case R.id.corky2:
// do something when the corky2 is clicked
break;
case R.id.corky3:
// do something when the corky3 is clicked
break;
default:
break;
}
}
}
What I'm trying to ask is, doing button2.setOnCLickListener() means - "Do what's set by this function for button2" right ? if not then what is the actual purpose/function performed by setOnClickListener() ?

Since you have set clickListeners to 3 different buttons, the method
....onClick(View v){.....
is going to get called when you click any of those 3 buttons. If you click the button1 you do not want to perform task actually assigned for button3. So to check and find out which button was pressed the switch statement is necessary.
Alternatively you could have done this:
corkyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// do something when the corky is clicked
}
});
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// do something when the play is clicked
}
});
so on and so forth...
This way you don't need a switch statement as in this case you know which button is being clicked on, AS you're setting the clickListener AND ALSO specifiying what you wanna do there itself.

It's more of a clean look, a more readable code style structure. If you have multiple widgets who need click listener, by implementing View.OnClickListener interface
and overriding onClick gives a cleaner look.
and inside onClick(View view){
- you can also use if statement but when the number of widgets is more
then it becomes messy, that's why we use switch statement to look cleaner.
}
and
btn.setOnClickListener(this)
// telling the button to pass the interface
so that overridden onClick can listen to this.
But If you don't want that or you have only one widget for click
then just use this, no need to implement and override.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});

Related

One OnClick handler for multiple buttons in a fragment

I have 3 buttons in a fragment that I want to use the same click event. How can this be achieved within a fragment?
XML
<Button
android:id="#+id/btn_1"
android:onClick="btnClick_DoSomething"
android:text="#string/one"/>
<Button
android:id="#+id/btn_2"
android:onClick="btnClick_DoSomething"
android:text="#string/two"/>
<Button
android:id="#+id/btn_3"
android:onClick="btnClick_DoSomething"
android:text="#string/three"/>
Java
#Override
public void btnClick_DoSomething(View v) {
}
Error
#Override (within the fragment Java class) becomes underlined in red and the following error is returned
Annontations are not allowed here
I want the onClick event to be the same for all 3 buttons
You dont need to write #Override annotation as you are not overriding the method. Just use
public void btnClick_DoSomething(View v) {
}
You will get a callback in this method at runtime.
you simply don't do it in XML, do it in Java instead:
<Button
android:id="#+id/btn_1"
android:text="#string/one"/>
<Button
android:id="#+id/btn_2"
android:text="#string/two"/>
<Button
android:id="#+id/btn_3"
android:text="#string/three"/>
then...
private final OnClickListener onClick = new OnClickListener(){
#Override
public void onClick(View view){
switch(view.getId()){
... cases...
}
}
somewhere initialising the views you do:
fragmentView.findViewById(R.id.btn_1).setOnClickListener(onClick);
fragmentView.findViewById(R.id.btn_2).setOnClickListener(onClick);
fragmentView.findViewById(R.id.btn_3).setOnClickListener(onClick);
}
What method are you trying to override? Do any of the parent classes have a method btnClick_DoSomething? You do not need to override anything when setting a click listener from a Layout XML. Just ensure that a method of the same name with a void return type and a View as its only argument exists in the activity class that will use this layout
The general way to distinguish clicks from different Views in the same onClick handler is to identify them by id
public void btnClick_DoSomething(View v){
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
There are some misunderstandings here. To override a Click event, your Fragment need to implement the View.OnClickListener interface like this:
public class YourFragment extends Fragment implements View.OnClickListener{
#Override
public void onClick(View v) {
}
}
Note that the name of the method must be onCLick, must return void and recives a View as a parameter to be overrided from the interface. In this case you need to set a Listener to each button in your fragment:
btn1 = (Button) view.findViewById(R.id.btn_1);
btn1.setOnClickListener(this);
Inside this method you can control which object was clicked by it´s ID
#Override
public void onClick(View v) {
int id = v.getId();
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
Or, you don't need to override the method, so remove the anotation that will work's fine :
public void btnClick_DoSomething(View v) {
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
Instead of declaring the onClick method in the xml layout file, you could have your Fragment implement View.onClickListener interface, override onClick(), and set all 3 buttons onClickListener like this btn.setOnClickListener(this). Put the behavior you want for all 3 buttons in onClick(). All 3 will have the same behavior (unless you check which button the event came from in onClick()).

What does the onclick listener (this) mean?

btn_Login.setOnClickListener(this);
In android studio.
I've seen this in countless places. What does this mean? I know how this operates but what is the listener called then?
This example is from: Link
Suppose that you have 16 Buttons and every button has setOnclicklistener this means that you are creating many repetitions of similar code to this in your class. And that makes your code ugly, also this is not the efficient way to write your code. So to make your code efficient you have to implement OnClickListener() on your activity and then for each button use buttonX.setOnClickListener(this). Now use the override onClick method. In this method, you can use either the switch case block or if-else to identify which button is pressed. So in the onClick method you just have to give ids of the button.
Implement OnClickListener in Activity
public class MyActivity extends Activity implements View.OnClickListener {
}
For each button use this:
buttonX.setOnClickListener(this);
After this implement override the onClick method
#Override
public void onClick(View view) {
switch(view.getId){
case R.id.buttonX:
// Do something
break;
}
in that example its defined like this
private Button btn_Login;
Button is a class
onClickListener is a listener, to set the listener he is using setOnClickListener method.
From the next time if u need to those kind of clarifications don't post in a separate thread, add a comment in that question itself.
Thank You #august alsina
It is a listener that helps to specify the events to occur on click of a widget.
When your class implement View.OnClickListener, you can defined your click of each button in method public void onClick(View v). Keyword this refer to the method onclick. It is good to use this way when there are a lot of button in your class file. You can define following code On Create method:
button1.setOnClickListener(this);
button2.setOnClickListener(this);
and define its definition oncreate method. For example:
public void onClick(View v){
int id= v.getId();
switch (id){
case R.id.btn1: {
//do sth
//break;
}
case R.id.btn2: {
//do sth
//break;
}
...
}
}
In layman's terms
By writing btn_Login.setOnClickListener(this);
whenever btn_login will be pressed program will go to onclick method public void onClick(View v)
and then you can write in the method what you want to do when button is pressed

Creating buttons and separating there functionality android

my app have action bar on top of windows. Where are some buttons. Buttons count and there functions is changing depending on activity user are.
I want to write a class with methods addFirstButton, removeFirstButton and so on.
So i other classes i want to do this:
MyButtons myButtons = new MyButtons();
myButtons.addFirstButton();
So there is everything alright, but how to create a listener button if i want to do this ?
Normally i would do this:
Button backButton = (Button) customNav.findViewById(R.id.back);
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(Action_Bar_TestingActivity.this, "BACK", Toast.LENGTH_SHORT).show();
}
});
But i want that this would be in MyButtons class and method somehow would return a listener to that action.
So any ideas if this possible ?
Thanks.
If you're programming an Action Bar, then you can handle its "buttons" in onOptionsItemSelected(). For more information, see here: http://developer.android.com/guide/topics/ui/menus.html
If you are supporting Android 1.6-2.x, you can make a copy of the ActionBarCompat sample app. It will use some of the same XML flags as >=3.x ActionBar, but not all functionality is emulated. You may also consider using Action Bar Sherlock.
If you want to set and get your onClickListeners, you can. Nothing says you have to instantiate the click listener inside the button. But you'll have to do some bookkeeping. At the least, instantiate the listener outside your button array and pass it in.
Here's how I make a standalone click listener:
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
}
};
And here's where I attach it to a button (trivial example):
private void setBtnListener(
Button btn,
Button.OnClickListener onClickListener ) {
btn.setOnClickListener(onClickListener);
}
(If you want to see what this function really looks like, it's part of the Capturing Photos sample app.)
But I think you can see how you could use this function internal to MyButtons.
Or the hard way to code:
final Button backButton = null;
final LinearLayout navBar = (LinearLayout) customNav.findViewById(R.id.root);
Button addButton = (Button) customNav.findViewById(R.id.add_button);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
if (backButton == null)
{
backButton = new Button(this);
backButton.setText("Back");
backButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Toast.makeText(Action_Bar_TestingActivity.this, "BACK", Toast.LENGTH_SHORT).show();
}
});
navBar.addView(backButton);
addButton.setText("Remove Back button");
}
{
navBar.removeView(backButton);
backButton = null;
addButton.setText("Add Back button");
}
}
});

What's the effect of implementing the OnClickListener with an Activity?

I don't understand why I have to implement the OnClickListener to use the OnClick-method. Assuming this code:
public class KlickitestActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onClick(View v) {
// code what happens when a click is made
}
From the class OnClickListener I only use the method onClick(View v) - and this one is overwritten. Why can't I just define the onClick-method without implementing the OnClickListener?
You can. You can do that by using an Anonymous Inner Class :
Button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Do stuff
}});
Button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
//Do stuff
}});
However implementing an OnClickListener makes it easier to handle events, and improves code readability. i.e You can use one Listener method, and passing a View to handle multiple buttons/listeners with a switch statement, something similar to :
public void onClick(View view){
switch(view.getId()){
case R.id.Button1:
//Stuff for button 1
break;
case R.id.Button2:
//Stuff for button 2
break;
break;
case R.id.Button3:
//Stuff for button 3
break;
}
Just to expand on Mob's answer and also Scott's comment and link...
An Activity is primarily a framework for a UI and as such has no pre-defined way of interacting with a user. As designers / developers we choose which UI components we want the Activity to contain based on the purpose of the Activity.
The UI components such as Buttons, CheckBoxes, ListViews and so on, serve very different purposes and it is not the place of an Activity in it's basic form to know what events those UI elements react to (click, long-click, swipe etc) simply because there is no pre-defined set of UI elements that an Activity will always host. As such it is our responsibility to implement the event handlers (listeners) that we need to use based on how we design the UI.

Can I reference an OnClickListener's button from inside the listener? (android)

I have an android program where I have multiple buttons using the same OnClickListener, and I want to be able to reference the button's dynamically assigned text from inside the listener. Is there some way to reference the button that was pushed to get its text? I don't want to have to make multiple button-specific listeners that do the same thing.
In your onClick(View v) you can cast it to a button:
#Override
public void onClick(View v) {
Button clickedButton = (Button)v;
// do stuff with it here.
}
use the View which comes as the argument to the onClick(View v)
this can be casted to a button & worked with.
The argument to onClick is the View that originated the click, which will be the button to which you attached the listener. Cast it to Button to get the button object.
Yes, there should be a way.
public abstract void onClick (View v)
You'll notice that the View that was clicked is passed into the onClick() method. So if you have a reference to the View (Button) available (for example, as an instance variable in the Activity) then you can do this:
public abstract void onClick (View v) {
if (v == firstButton) {
//Do some stuff
}
else if (v == secondButton) {
//Do some other stuff
}
}

Categories