So right now I'm tidying up some code, and I have a lot of else/ifs for buttons and was wondering what is a good way to do it and make it neater?
So I have like 12 buttons, and each button plays a sound and changes colour when clicked. I have a method for this but I was wondering is there a good way to just detect the button instead of if/else?
public void onClick(View v) {
int id = v.getId();
changeToWhite();
if (id == R.id.a_button) {
currentButton(a, 81);
} else if (id == R.id.aSharp_button) {
currentButton(aSharp, 82);
} else if (id == R.id.b_button) {
currentButton(b, 83);
} else if (id == R.id.c_button) {
currentButton(c, 72);
}
Etc...
So is there a better way of having this? I know having a lot of else/ifs is bad so I wanted to try improve it.
Thanks!!
You can use "switch-case" instead.
>
public void onClick(View v) {
switch(v.getId())
{
case R.id.a_button:
changeToWhite();
break;
case R.id.aSharp_button:
currentButton(aSharp,82);
break;
.....
default:
break;
}
}
How about using a case statement instead?
public void onClick(View v) {
// Perform action on click
switch(v.getId()) {
case R.id.a_button:
currentButton(a, 81);
break;
case R.id.aSharp_button:
currentButton(aSharp, 82);
break;
/*
and the rest of the cases here.
*/
}
}
I assume you're using XML and setting the onClick property.
An easier/tidier way is to use anonymous inner classes.
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foo);
findViewById(R.id.view_buttonone).setOnClickListener(new OnClickListener(){
public void onClick(View view){
// button one clicked
}
});
findViewById(R.id.view_buttontwo).setOnClickListener(new OnClickListener(){
public void onClick(View view){
// button two clicked
}
});
}
First of all there is virtually no penalty for using if/else nesting. There's no need to try this level of micromanaging your app. You will gain no benefits from it. Try to think more of optimizing this point in terms of readability.
Now, to answer your question, you could use a switch/case construct instead.
public void onClick(View v) {
switch (item.getItemId()) {
case R.id.aBar_item1:
//Item onClick logic
return true;
case R.id.aBar_item2:
//Item onClick logic
return true;
case R.id.aBar_item3:
//Item onClick logic
return true;
...
}
}
Related
I was wondering If anyone knew of a way getting the On Click Listener a button is set to. Sort of like...
btn1.getOnClickListner
I want to make an IF Statement like this...
if (button.Onclick == onClick1) {
do this...
} else {
do this...
}
Any Help would be much Appreciated
I found the easiest way to do this was to take CommonsWares advice and create one onClick, using booleans to give it separate methods to execute. Below is an example in case anyone else gets stuck trying to accomplish this task. Thank you to everyone that helped and shared their thoughts.
public class MainActivity extends Activity implements View.OnClickListener {
boolean separateOnClickActive;
Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.button);
btn1.setOnClickListener(this);
separateOnClickActive = false;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
if (!separateOnClickActive) {
// Do Something Here
separateOnClickActive = true;
} else {
//Do Something Here
}
break;
}
}
}
I'm developing an Android app and I have a question:
Is there a way to pause a method until the user presses a view? I am considering doing something like this:
Make a boolean for my class called "wait".
When someone clicks on the view, it will change the boolean to true.
Finally, in the main method, do something like:
while (!wait)
{
//do nothing
}
Is there any better way to do this?
I suppose you are doing it like this...
boolean wait = false;
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
doSomething();
break;
case R.id.button2:
wait = true;
break;
}
}
public void doSomething() {
//
// Do Task 1
//
while(!wait) {}
//
// Do Task 2
//
}
Instead, you can perform it like this...
boolean viewClicked = false;
public void onClick(View v) {
switch(v.getId())
{
case R.id.button1:
doSomething();
break;
case R.id.button2:
viewClicked = true;
doSomething();
break;
}
}
public void doSomething() {
if(!viewClicked)
{
//
// Do Task 1
//
}
else
{
//
// Do Task 2
//
}
}
I hope this helps. :)
I wanted to make a plain button in the menu act as a on/off button like a toggle button. But I'm not sure how I can make a single button act like a switch?
switch(item.getItemId()){
case R.id.switcher:
View view = this.getWindow().getDecorView();
view.setBackgroundColor(Color.parseColor("#80FFFFFF"));
//I want to change the color of the background by clicking once
//and set the background color back to normal. How will I achieve this ?
return true;
Try this:
#Override
public void onClick(View v) {
if ((v.getId() == R.id.my_button){
buttonOnClick(v);
}
}
private void buttonOnClick(View v) {
switch (v.getId()) {
case R.id.my_button: {
if (v.isSelected()) {
// is selected, deselect!
v.setSelected(false);
//do your staff here
} else {
// is not selected, select!
v.setSelected(true);
//do your staff here
}
break;
}
default:
break;
}
I have 10 buttons set up which are the answers to ten questions. When a certain button is clicked, I have a switch statement set up in my onClick method shown below. My question is what is the best way to set up the OnClickListeners for all the buttons seeing that I need to pass 2 arrays to the onClick method in order to tell if it is correct or not? Also, I need to return and integer value. Thanks
public void onClick(View v, int[] qaarray, int questionorder) {
int x=0;
switch(v.getId())
{
case R.id.imageButton0:
if(qaarray[0] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton1:
if(qaarray[1] == questionorder){
// correct
}else{
//incorrect
}
break;
case R.id.imageButton2:
if(qaarray[2] == questionorder){
// correct
}else{
//incorrect
}
break;
case R.id.imageButton3:
if(qaarray[3] == questionorder){
// correct
}else{
//incorrect
}
break;
case R.id.imageButton4:
if(qaarray[4] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton5:
if(qaarray[5] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton6:
if(qaarray[6] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton7:
if(qaarray[7] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton8:
if(qaarray[8] == questionorder){
//correct
}else{
//incorrect
}
break;
case R.id.imageButton9:
if(qaarray[9] == questionorder){
//correct
}else{
//incorrect
}
break;
default:
throw new RuntimeException("Unknown button ID");
}
}
The OnClickListener only gives you one parameter, which is the View:
void onClick(View v);
But you don't have to pass the questions and 'order' to the method to have what you want. One of the technique you can use is the setTag() method of View:
int[] button = new int[] { R.id.imageButton1, R.id.imageButton2.... };
private class AnswerPair{
public int questionOrder;
public int answer;
}
public void onCreate(Bundle bundle){
for(int i=0; i<NO_OF_BUTTON; i++){
AnswerPair ans = new AnswerPair();
ans.questionOrder = i;
ans.answer = 0; // SET this
getViewById(button[i]).setTag(ans);
getViewById(button[i]).setOnClickListener(this);
}
}
public void onClick(View v){
if (v.getTag() == null) return;
try{
AnswerPair answer = (ans)v.getTag();
// Check answer == question order? index?
}catch(exception e) return;
}
You can implement as many OnClickListeners as you want and assign different listeners for each button.
public void onCreate(Bundle bundle){
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.myButton)
b.setOnClickListener(new MyListener());
}
private class MyListener implements OnClickListener {
#Override
public void onClick(View v) {
// Your code here
}
}
i think a lot of people know this already, but there's a shortcut you can use instead of having different instances of onClickListeners and assigning them in code using setOnClickListener(x).
In your button XML, give it the android:onClick property, and assign it a string you like, for example,
android:onClick="clickOne"
In the activity the sets this xml as its content view, create a method named clickOne with a View parameter.
public void clickOne(View view)
Whatever you place on this method will be executed when you click the button.
imgvw_back.setOnClickListener(this);
imgvw.setOnClickListener(this);
static id=10
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.back:
Log.v("back",""+id--);
break;
case R.id.forward:
Log.v("next",""+id++);
break;
}
}
i am using this kind of concept but mostly fire R.id.back part ,what can i do plz give solution for this problem...
The id may not be what you think it is, you could do something like this.
imgvw_back.setOnClickListener(this);
imgvw.setOnClickListener(this);
static id=10
#Override
public void onClick(View v)
{
if(v == imgvw_back)
{
Log.v("back",""+id--);
}
else if(v == imgvw)
{
Log.v("next",""+id++);
}
}
Use inline onClickListeners for each button.
imgvw_back.setOnClickListener(new onClickListener(){
#Override
public void onClick(View v){
Log.v("back", "")
}
});
Is imgvw your forward button? Just wondering, cause your back button is imgvw_back, would assume forward would be named accordingly imgvw_forward.
You're probably missing missing to set the clickListener to the forward button as well.