PreferenceFragment public void onAttach(Context pContext) not work

  • 内容
  • 评论
  • 相关
public class FragmentSetting extends PreferenceFragment {}
@Override
public void onAttach(Context pContext) {
 //not working
 super.onAttach(pContext);
 if (pContext instanceof AppCompatActivity){
 mActivity = (AppCompatActivity)pContext;
 }
}

@Override
public void onAttach(Activity pActivity) {
 //is working
 super.onAttach(pActivity);
 mActivity = pActivity;
}

最近发现PreferenceFragment中public void onAttach(Context pContext) {}并不执行,是Android的一个BUG。
但是public void onAttach(Activity pActivity) {}又不建议使用了。
/**
 * Called when a fragment is first attached to its context.
 * {@link #onCreate(Bundle)} will be called after this.
 */
public void onAttach(Context context) {
    mCalled = true;
    final Activity hostActivity = mHost == null ? null : mHost.getActivity();
    if (hostActivity != null) {
        mCalled = false;
        onAttach(hostActivity);
    }
}

/**
 * @deprecated Use {@link #onAttach(Context)} instead.
 */
@Deprecated
public void onAttach(Activity activity) {
    mCalled = true;
}

希望google的工程师们进行修复,目前还是使用public void onAttach(Activity pActivity) {}
来解决现有的问题,也可以两种方法都使用。