如何从首选项片段中设置结果?



我使用 Android Studio 向导创建了一个"设置"活动。在此活动中是以下 PreferenceFragment 类。

public static class MyPreferenceFragment extends PreferenceFragment
{
...
}

我在这个 PreferenceFragment 类中有一些侦听器,我想从 PreferenceFragment 类中设置结果((。但是我遇到崩溃"方法未找到异常"。

如何访问活动/设置结果?

片段不能有"结果",你应该在活动中调用它。

您可以在任何想要设置结果的地方执行此操作:

Activity activity = getActivity();
//activity in fragment is nullable, 
//so null check is suggested to avoid NullPointerException
if (activity != null) {
activity.setResult(RESULT_OK);
activity.finish();
}

最新更新