我有一个片段(F1)与这样的公共方法

public void asd() {
    if (getActivity() == null) {
        Log.d("yes","it is null");
    }
}

是的,当我调用它(从活动),它是空…

FragmentTransaction transaction1 = getSupportFragmentManager().beginTransaction();
F1 f1 = new F1();
transaction1.replace(R.id.upperPart, f1);
transaction1.commit();
f1.asd();

一定是我做错了什么,但我不知道是什么。


当前回答

最好的办法是在onAttach被调用时保持活动引用,并在任何需要的地方使用活动引用。

@Override
public void onAttach(Context context) {
    super.onAttach(activity);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    mContext = null;
}

其他回答

PJL是对的。 我采纳了他的建议,我是这样做的:

为fragment定义的全局变量: attachingActivityLock = new Object(); private boolean syncVariable = false; 实现

@Override onAttach(Activity Activity) { super.onAttach(活动); synchronized (attachingActivityLock) { syncVariable = true; attachingActivityLock.notifyAll (); } }

3.我在线程中包装了我的函数,在那里我需要调用getActivity(),因为如果它将在主线程上运行,我将用步骤4阻塞线程。onAttach()将永远不会被调用。

    Thread processImage = new Thread(new Runnable() {

        @Override
        public void run() {
            processImage();
        }
    });
    processImage.start();

4所示。在我的函数中,我需要调用getActivity(),我使用这个(在调用getActivity()之前)

    synchronized (attachingActivityLock) {
        while(!syncVariable){
            try {
                attachingActivityLock.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

如果你有一些UI更新,记得在UI线程上运行它们。我需要更新ImgeView,所以我做了:

image.post(new Runnable() {

    @Override
    public void run() {
        image.setImageBitmap(imageToShow);
    }
});

在onActivityCreated()中调用getActivity()方法

编写一个通用方法,确保永远不会得到空Activity。

public class BaseFragment extends Fragment {
    private Context contextNullSafe;

     @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
         /*View creation related to this fragment is finished here. So in case if contextNullSafe is null
         * then we can populate it here.In some discussion in - https://stackoverflow.com/questions/6215239/getactivity-returns-null-in-fragment-function
         * and https://stackoverflow.com/questions/47987649/why-getcontext-in-fragment-sometimes-returns-null,
         * there are some recommendations to call getContext() or getActivity() after onCreateView() and
         * onViewCreated() is called after the onCreateView() call every time */
        if (contextNullSafe == null) getContextNullSafety();
    }


   @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        contextNullSafe = context;
    }

    /**CALL THIS IF YOU NEED CONTEXT*/
    public Context getContextNullSafety() {
                if (getContext() != null) return getContext();
                if (getActivity() != null) return getActivity();
                if (contextNullSafe != null) return contextNullSafe;
                if (getView() != null && getView().getContext() != null) return getView().getContext();
                if (requireContext() != null) return requireContext();
                if (requireActivity() != null) return requireActivity();
                if (requireView() != null && requireView().getContext() != null)
                    return requireView().getContext();
                
                return null;
            
        }

    /**CALL THIS IF YOU NEED ACTIVITY*/
    public FragmentActivity getActivityNullSafety() {
        if (getContextNullSafety() != null && getContextNullSafety() instanceof FragmentActivity) {
            /*It is observed that if context it not null then it will be
             * the related host/container activity always*/
            return (FragmentActivity) getContextNullSafety();
        }
        return null;
    }

最好的办法是在onAttach被调用时保持活动引用,并在任何需要的地方使用活动引用。

@Override
public void onAttach(Context context) {
    super.onAttach(activity);
    mContext = context;
}

@Override
public void onDetach() {
    super.onDetach();
    mContext = null;
}

在commit()之后调用回调函数的顺序:

无论你在commit()之后手动调用什么方法 onAttach () onCreateView () onActivityCreated ()

我需要做一些涉及一些视图的工作,所以onAttach()不适合我;它坠毁。所以我移动了我的代码的一部分,设置一些参数在一个方法调用后立即提交()(1.),然后在onCreateView()(3.)内处理视图的代码的另一部分。