Android - Handling a grid

笑着哭i 提交于 2019-12-11 19:52:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!