1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.incallui;
18
19import android.app.Activity;
20import android.app.Fragment;
21import android.os.Bundle;
22
23/**
24 * Parent for all fragments that use Presenters and Ui design.
25 */
26public abstract class BaseFragment<T extends Presenter<U>, U extends Ui> extends Fragment {
27
28    private static final String KEY_FRAGMENT_HIDDEN = "key_fragment_hidden";
29
30    private T mPresenter;
31
32    public abstract T createPresenter();
33
34    public abstract U getUi();
35
36    protected BaseFragment() {
37        mPresenter = createPresenter();
38    }
39
40    /**
41     * Presenter will be available after onActivityCreated().
42     *
43     * @return The presenter associated with this fragment.
44     */
45    public T getPresenter() {
46        return mPresenter;
47    }
48
49    @Override
50    public void onActivityCreated(Bundle savedInstanceState) {
51        super.onActivityCreated(savedInstanceState);
52        mPresenter.onUiReady(getUi());
53    }
54
55    @Override
56    public void onCreate(Bundle savedInstanceState) {
57        super.onCreate(savedInstanceState);
58        if (savedInstanceState != null) {
59            mPresenter.onRestoreInstanceState(savedInstanceState);
60            if (savedInstanceState.getBoolean(KEY_FRAGMENT_HIDDEN)) {
61                getFragmentManager().beginTransaction().hide(this).commit();
62            }
63        }
64    }
65
66    @Override
67    public void onDestroyView() {
68        super.onDestroyView();
69        mPresenter.onUiDestroy(getUi());
70    }
71
72    @Override
73    public void onSaveInstanceState(Bundle outState) {
74        super.onSaveInstanceState(outState);
75        mPresenter.onSaveInstanceState(outState);
76        outState.putBoolean(KEY_FRAGMENT_HIDDEN, isHidden());
77    }
78
79    @Override
80    public void onAttach(Activity activity) {
81        super.onAttach(activity);
82        ((FragmentDisplayManager) activity).onFragmentAttached(this);
83    }
84}
85