试图在android中传递参数

时间:2015-12-09 14:36:56

标签: java android function parameter-passing

所以我有两个文件(MainActivity.javaHomeFragment.java),我正在尝试将public static void displayPromptForEnablingGPSHomeFragment传递到MainActivity }。这是代码

HomeFragment.java(我试图通过的代码)

public static void displayPromptForEnablingGPS(
        final Activity activity)
{
    final AlertDialog.Builder builder =
            new AlertDialog.Builder(activity);
    final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
    final String message = "Enable either GPS or any other location"
            + " service to find current location.  Click OK to go to"
            + " location services settings to let you do so.";


    builder.setMessage(message)
            .setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface d, int id) {
                            activity.startActivity(new Intent(action));
                            d.dismiss();
                        }
                    })
            .setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface d, int id) {
                            d.cancel();
                        }
                    });
    builder.create().show();
}

MainActivity.java(我打算怎么称呼它)

public void showMainView() {
   HomeFragment.displayPromptForEnablingGPS();
}

但我收到错误

"HomeFragment.displayPromptForEnablingGPS();" is invalid

1 个答案:

答案 0 :(得分:1)

您要调用的方法需要一个参数,但您不能通过它。

public static void displayPromptForEnablingGPS(
    final Activity activity)

您在MainActivity中的方法应如下所示:

public void showMainView() {
   HomeFragment.displayPromptForEnablingGPS(this);
}