如何在片段中使用 public 方法

How to use public method in fragment

我正在拨打电话拦截器。我正在尝试 运行 在片段中的 mainActivity 中运行的代码。

    @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_READ_PHONE_STATE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(getActivity(), "Permission granted" +PERMISSION_REQUEST_READ_PHONE_STATE , Toast.LENGTH_SHORT).show();

            } else {
                Toast.makeText(getActivity(), "Permission NOT granted: " + PERMISSION_REQUEST_READ_PHONE_STATE, Toast.LENGTH_SHORT).show();
            }

            return;
        }
    }
}

onCreateView=

   @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_call, container, false);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
        if (getActivity().checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_DENIED || getActivity().checkSelfPermission(Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_DENIED) {
            String[] permissions = {Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE};
            requestPermissions(permissions, PERMISSION_REQUEST_READ_PHONE_STATE);
        }
    }

    onRequestPermissionsResult();

    return view;
}

问题是public void onRequestPermissionsResult 它上面有一行,当我将鼠标悬停在它上面时,“onRequestPermissionsResult”会显示此消息。尝试了几种方法和方式,希望有人能帮我解决。

那是 Activity 托管您的 Fragment 吗?如果是这种情况,您可以在 Fragment 中使用 getActivity() 并将其转换为 MainActivity.

((MainActivity)getActivity()).onRequestPermissionsResult();

但是,如果情况并非如此,请提供更多详细信息,因为您不应尝试访问与您的片段无关的任何活动。