使用相同方法的多个片段

时间:2017-01-18 07:13:10

标签: java android android-fragments android-activity

我有5个片段,每个片段类都有完全相同的方法:

public class FirstFragment extends Fragment {
    // other methods

    public void clear() {
        data.clear();
        adapter.notifyDataSetChanged();
    }
}

第二个片段:

public class SecondFragment extends Fragment {
    // other methods

    public void clear() {
        data.clear();
        adapter.notifyDataSetChanged();
    }
}

等等......

如何更好地组织我的代码,以便我不必将此方法复制并粘贴到我的5个片段中(即制作一个方法,在每个片段中调用相同的方法)。

1 个答案:

答案 0 :(得分:4)

您需要使用Inheritance的概念,将所有常见变量和方法放在BaseFragment中,并从中扩展其他变量和方法。

public class BaseFragment extends Fragment {
public Data data;
public Adapter adapter;
        public void clear() {
            data.clear();
            adapter.notifyDataSetChanged();
        }
    }

首先:

public class FirstFragment extends BaseFragment {
    // other methods
}

第二

public class SecondFragment extends BaseFragment {
    // other methods
}