如何从PreferenceFragment中setResult?

时间:2018-06-11 11:47:23

标签: android android-fragments preferencefragment

我使用Android Studio向导创建了“设置”活动。在此活动中是以下PreferenceFragment类..

public static class MyPreferenceFragment extends PreferenceFragment
{
...
}

我在PreferenceFragment类中有一些监听器,我想从PreferenceFragment类中调用setResult()。但是我遇到了崩溃“找不到异常的方法”。

如何访问activity / setResult?

1 个答案:

答案 0 :(得分:1)

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

你可以在任何想要设置结果的地方这样做:

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();
}
相关问题