简单的Java问题

时间:2011-04-15 15:47:01

标签: java android

示例1 - 工作

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));
}
}

示例2 - 不起作用

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));
         }
}

为什么示例2不起作用?

1 个答案:

答案 0 :(得分:4)

您正尝试在此行上静态调用非静态方法:

Secondary.Test (MainScreen.this, touchedButton.getId());

您需要创建Secondary的实例并在实例上调用Test()或将Secondary.Test()更改为静态方法,如下所示:

public static void Test (MainScreen mainscreen, int touchedButton) {