Android fragment 回调函数改进

由于fragment的onResume()等回调的调用时机与Activity不一样,导致用起来比较麻烦,所以我重新封装了一下回调函数,十分简单。

使用时只需要继承此基类,使用onFragmentXXX系列回调即可。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
public class AbsFragment extends Fragment {
     
    /*-------------------------------------
     * 属性
     *-------------------------------------*/
    /**是否已经onResume()了*/
    private boolean isResume = false;
    /**setUserVisibleHint(boolean)传入的值*/
    private boolean isVisbleToUser = false;
 
    /*-------------------------------------
     * protected方法
     *-------------------------------------*/
    /**
     * Fragment创建时调用的函数,建议子类重写这个方法因为生命周期比较简单
     * @param savedInstanceState
     */
    protected void onFragmentCreate(Bundle savedInstanceState) {
         
    }
     
    /**
     * Fragment销毁时调用的函数,建议子类重写这个方法因为生命周期比较简单
     * @param savedInstanceState
     */
    protected void onFragmentDestroy() {
         
    }
     
    /**
     * Fragment可见时调用的函数,建议子类重写这个方法因为生命周期比较简单
     * @param savedInstanceState
     */
    protected void onFragmentResume() {
         
    }
     
    /**
     * Fragment不可见时调用的函数,建议子类重写这个方法因为生命周期比较简单
     * @param savedInstanceState
     */
    protected void onFragmentPause() {
         
    }
    /*-------------------------------------
     * public方法
     *-------------------------------------*/
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         
        onFragmentCreate(savedInstanceState);
    }
 
    @Override
    public void onDestroy() {
        onFragmentDestroy();
         
        super.onDestroy();
    }
     
    @Override
    public void onResume() {
        super.onResume();
         
        isResume = true;
        if(isVisbleToUser) {
            onFragmentResume();
        }
    }
 
    @Override
    public void onPause() {
        isResume = false;
        if(isVisbleToUser) {
            onFragmentPause();
        }
         
        super.onPause();
    }
     
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
         
        this.isVisbleToUser = isVisibleToUser;
        if(isResume) {
            if(isVisibleToUser) {
                onFragmentResume();
            } else {
                onFragmentPause();
            }
        }
    }
 
}

  

Android fragment 回调函数改进

上一篇:优化UI界面会惹怒用户?你应该这么做


下一篇:焦点移动幻灯片 swipe effect slider