Example 1 - works
public class MainScreen extends Activity implements OnClickListener {
public void onClick(View v) {
Button touchedButton = (Button) v;
Test (MainScreen.this, touchedButton.getId());
}
开发者_运维问答 public void Test (MainScreen mainscreen, int touchedButton) {
if (touchedButton == R.id.serviceButton )
startService(new Intent(mainscreen, SimpleService.class));
if (touchedButton == R.id.cancelButton)
stopService(new Intent(mainscreen, SimpleService.class));
}
}
Example 2 – does not work
public class MainScreen extends Activity implements OnClickListener {
public void onClick(View v) {
Button touchedButton = (Button) v;
Secondary.Test (MainScreen.this, touchedButton.getId());
}
}
public class Secondary extends Activity {
public void Test (MainScreen mainscreen, int touchedButton) {
if (touchedButton == R.id.serviceButton )
startService(new Intent(mainscreen,SimpleService.class));
if (touchedButton == R.id.cancelButton)
stopService(new Intent(mainscreen,SimpleService.class));
}
}
Why does Example 2 not work?
You're trying to call a non-static method statically on this line:
Secondary.Test (MainScreen.this, touchedButton.getId());
You need to create an instance of Secondary
and call Test()
on the instance or change Secondary.Test()
to be a static method like this:
public static void Test (MainScreen mainscreen, int touchedButton) {
精彩评论