onActivityCreated方法在一个片段中调用,但不在其他片段中调用

时间:2013-04-04 08:53:33

标签: android user-interface android-fragments

我正在开发一个平板电脑应用程序。我创建了一个用于List Of Item的片段和其他用于项目细节的片段。片段class.both片段中有onActivityCreated个方法用于一个actvity类。我有一个问题,即为一个活动而不是其他活动调用onActivityCreated方法。我想问一下onActivityCreated如何工作。我想调用第二个片段actvity onActvityCreated方法的方法。 请帮我。提前致谢

2 个答案:

答案 0 :(得分:2)

在创建Fragment之后调用

onActivityCreated(),就像创建Activity时调用onCreate()一样。要了解frament lifecylce,请单击here

答案 1 :(得分: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
    }
}