2

我正在开发一个平板电脑应用程序。我已经创建了一个用于项目列表的片段和另一个用于项目细节的片段。两个片段类中都有onActivityCreated方法。两个片段都用于一个活动类。我有一个问题,onActivityCreated即为一项活动而不是其他活动调用方法。我想问它是如何onActivityCreated工作的。我想为第二个片段活动方法调用一个onActvityCreated方法。请帮我。提前致谢

4

2 回答 2

2

onActivityCreated()在创建 Fragment 之后调用,就像onCreate()在创建 Activity 时调用一样。要了解框架生命周期,请单击此处

于 2013-04-04T11:00:46.287 回答
1

我使用观察者模式并让我的片段注册以获得活动结果。

public abstract class MyActivity {

    protected static Set<ActivityListener> mListenerSet = Collections.synchronizedSet(new HashSet<ActivityListener>(4,0.75f));

    public interface ActivityListener {
        public void onActivityResult(int requestCode, int resultCode, Intent data);
    }

    /**
     * @brief Register for getting {@link MyActivity#onActivityResult(int, int, Intent)} calls 
     *
     * @param listener Callback according to interface {@link ActivityListener}
     */
    public void registerListener(ActivityListener listener) {
        MyLog.v(LOG_TAG, "registerListener()");
        mListenerSet.add(listener);
    }

    /**
     * @brief Unregister to stop receiving {@link Activity#onActivityResult(int, int, Intent)} calls 
     *
     * @param listener Callback according to interface {@link ActivityListener}
     */
    public void unregisterListener(ActivityListener listener) {
        MyLog.v(LOG_TAG, "unRegisterListener()");
        mListenerSet.remove(listener);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        for (ActivityListener listener : mListenerSet) {
            listener.onActivityResult(requestCode, resultCode, data);
        }
    }
}

然后让你的片段实现 ActivityListener

public class MyFragment extends Fragment implements ActivityListener {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ((MyActivity) getActivity()).registerListener(this);
        [...]
    }

    @Override
    protected void onDestroyView() {
        super.onDestroyView();
        ((MyActivity) getActivity()).unregisterListener(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //Do your stuff here
    }
}
于 2013-04-04T09:05:22.943 回答