Android - Handling a grid

2019-08-17 16:56发布

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条回答
家丑人穷心不美
2楼-- · 2019-08-17 17:29

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
   }
}
查看更多
登录 后发表回答