问题
I am trying to make a 2x2 grid of buttons and handle them. Right now I have a relative view activity with four buttons...but my question is: is the best way to do this? Than give each button a listener? Or is there anyway to add the buttons to the GridView and handle them all in one method? Ex.: Instead of using something like if(button1x1)... if(button1x2)... if(button2x2)... if(button2x1)... and write a method for all of them, is there a way for me to just have one method and it will automatically detect which button is being pushed? Sorry if this is a confusing question, I can think it perfectly but translating to words is a bit difficult. Thanks for any help!
回答1:
First of you you can do
public class YourActivity extends Activity implements OnClickListener {...
and then implement the onClick method as
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.A_UI_Element:
//do what you need for this element
break:
case R.id.A_Different_UI_Element:
//do what you need for this element
break;
//continue with cases for each element you want to be clickable
}
}
来源:https://stackoverflow.com/questions/21321996/android-handling-a-grid