summaryrefslogtreecommitdiffhomepage
path: root/app/src/main/java/com/wireguard/android/fragment/BaseFragment.java
blob: 5383e77fe70388915ba41a88911599afbfb5ecb0 (plain)
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
/*
 * Copyright © 2018 Samuel Holland <samuel@sholland.org>
 * Copyright © 2018 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
 * SPDX-License-Identifier: GPL-2.0-or-later
 */

package com.wireguard.android.fragment;

import android.content.Context;
import android.support.v4.app.Fragment;

import com.wireguard.android.activity.BaseActivity;
import com.wireguard.android.activity.BaseActivity.OnSelectedTunnelChangedListener;
import com.wireguard.android.model.Tunnel;

/**
 * Base class for fragments that need to know the currently-selected tunnel. Only does anything when
 * attached to a {@code BaseActivity}.
 */

public abstract class BaseFragment extends Fragment implements OnSelectedTunnelChangedListener {
    private BaseActivity activity;

    protected Tunnel getSelectedTunnel() {
        return activity != null ? activity.getSelectedTunnel() : null;
    }

    @Override
    public void onAttach(final Context context) {
        super.onAttach(context);
        if (context instanceof BaseActivity) {
            activity = (BaseActivity) context;
            activity.addOnSelectedTunnelChangedListener(this);
        } else {
            activity = null;
        }
    }

    @Override
    public void onDetach() {
        if (activity != null)
            activity.removeOnSelectedTunnelChangedListener(this);
        activity = null;
        super.onDetach();
    }

    protected void setSelectedTunnel(final Tunnel tunnel) {
        if (activity != null)
            activity.setSelectedTunnel(tunnel);
    }
}