switch/case只能判断int类型的变量,就从这点入手,代码还是比较清楚的,两种方法均来自StackOverflow
方法一:
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ImageView img1 = (ImageView)findViewById(R.id.img1); ImageView img2 = (ImageView)findViewById(R.id.img2); img1.setOnClickListener(new OnClickEvent()); img2.setOnClickListener(new OnClickEvent());}private class OnClickEvent implements OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.img1: System.out.println("click img1"); break; case R.id.img2: System.out.println("click img2"); break; default: break; } }}
方法二:
@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ImageView img1 = (ImageView)findViewById(R.id.img1); ImageView img2 = (ImageView)findViewById(R.id.img2); img1.setId(R.string.app_name); img2.setId(12); img1.setOnClickListener(new OnClickEvent()); img2.setOnClickListener(new OnClickEvent());}private class OnClickEvent implements OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.string.app_name: System.out.println("click img1"); break; case 12: System.out.println("click img2"); break; default: break; } }}
可以看到第二种方法很有意思,我们人为地给View一个Id就行了,这个Id甚至可以是R.string.app_name这种东西,因为R.string.app_name还是一个int类型的变量