Question 1: Unfortunately, the one you are talking about is the most intuitive, least used on Android. As far as I understand, you should separate your user interface (XML) and computational functionality (Java class files). It also simplifies debugging. It is actually much easier to read this way and think about Android imo.
Question 2: I believe that two and # 3 are mainly used. As an example, I use ButtonButton.
2
is in the form of an anonymous class.
Button clickButton = (Button) findViewById(R.id.clickButton); clickButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) {
This is my favorite as it has an onClick method next to where the button variable was set using findViewById. It seems very neat and tidy that everything related to this ButtonButton mouse click is here.
The con my colleague comments on is that you imagine you have a lot of views that need an onclick listener. You can see that your onCreate will be very long. Therefore, he likes to use:
3
Say what you have, 5 clicks:
Make sure your Activity / Fragment implements OnClickListener
// in OnCreate Button mClickButton1 = (Button)findViewById(R.id.clickButton1); mClickButton1.setOnClickListener(this); Button mClickButton2 = (Button)findViewById(R.id.clickButton2); mClickButton2.setOnClickListener(this); Button mClickButton3 = (Button)findViewById(R.id.clickButton3); mClickButton3.setOnClickListener(this); Button mClickButton4 = (Button)findViewById(R.id.clickButton4); mClickButton4.setOnClickListener(this); Button mClickButton5 = (Button)findViewById(R.id.clickButton5); mClickButton5.setOnClickListener(this); // somewhere else in your code public void onClick(View v) { switch (v.getId()) { case R.id.clickButton1: { // do something for button 1 click break; } case R.id.clickButton2: { // do something for button 2 click break; } //.... etc } }
Thus, as my colleague explains, it is accurate in the eyes, since all onClick calculations are processed in one place and do not overwhelm the onCreate method. But the drawback that I see is that:
- looking at themselves
- and any other object that can be located in onCreate used by the onClick method must be made in the field.
Let me know if you want more information. I did not fully answer your question, because it is a rather long question. And if I find several sites, I will expand my answer, right now I'm just giving some experience.
D. Tran Feb 08 '13 at 23:44 2013-02-08 23:44
source share