Reputation: 3043
I'm learning android development from Udacity course created by google, in an exercise, it is asked to create a score record for two teams playing basketball.
the app looks like :
You can guess what each button does ....
To do that they create 6 methods (addThreePointToTeamA, addTwoPointToTeamA...) for each button. but I think that two methods (addTeamA, addTeamB) are enough if I could pass an int parameter correspond to the number of points to add to each method .
So I wonder if it is possible to do that ? and if not, why ?
Thank you in advance
EDIT
here is what I wish to do :
in the layout.xml :
<Button
...
android:text="+3 POINTS"
android:onClick="addThreeTeamA(3)"
/>
then in the MainActivity.java:
public void addThreeTeamA(int point){
....
}
Upvotes: 0
Views: 501
Reputation: 1798
It is technically possible to implement just only one Click Listener but not in the way you asked for since there is no a way to pass parameter to a click listener. Instead, you need to define android:id
for every single button and use this approach.
public void buttonClicked(View v) {
switch (v.getId()) {
case R.id.btnAddTeamAThree:
// Add 3 points to Team A
break;
case R.id.btnAddTeamATwo:
// Add 2 points to Team A
break;
case R.id.btnAddTeamBThree:
// Add 3 points to Team B
break;
case R.id.btnAddTeamBTwo:
// Add 2 points to Team B
break;
...
}
}
Upvotes: 3
Reputation: 5
They created 6 methods for your better understanding. Once you get what they want to perform than you can enhance it. Yes you can enhance it by making generic methods for team-A and team-B. Its totally depend on your logic. Hope i answer your question.
Upvotes: 0
Reputation: 13922
The answer is simple you can definitely do that.
I would say, think about your design though.
Here is what I would Recommend:
// Setup an interface for common team behaviors
interface Team {
void addPoints(int points);
int getPoints();
}
// implement that interface per Team
class TeamA implements Team {
private int points;
public TeamA(){
this.points = 0;
}
@Override
public void addPoints(int points){
this.points += points;
}
@Override
public int getPoints(){
return this.points;
}
}
And do the same for TeamB!
then create a method in your Activity or whatever class your calling to add from:
public void addPoints(int points, Team team){
team.addPoints(points);
}
Good Luck and Happy Coding!
Upvotes: 1