java - 使用相同方法的多个 fragment

标签 java android android-fragments android-activity

我有 5 个 fragment ,其中每个 fragment 类都有完全相同的方法:

public class FirstFragment extends Fragment {
    // other methods

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

第二个 fragment :

public class SecondFragment extends Fragment {
    // other methods

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

等等……

我怎样才能更好地组织我的代码,这样我就不必将此方法复制并粘贴到我的 5 个 fragment 中的每一个(即制作一个方法,在每个 fragment 中调用相同的方法)。

最佳答案

你需要使用Inheritance的概念,将所有公共(public)变量和方法放在 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
}

关于java - 使用相同方法的多个 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41713354/

相关文章:

java - RabbitMQ:如何限制路由键格式

java - 我收到错误“远程 URL 测试失败 : protocol 'git clone HTTPS ' is not supported"when i enter the url field

Android - 重启后打开系列 Activity

java - Intent Data 中的 Integer putExtra() 被设置为 ParcelledData 导致 AsyncTask 异常?

android - View 绑定(bind)无权访问 fragment

android - 在单个 fragment 中处理后退按钮

android - Google Map Fragment 和 AdMob, map 位置按钮在广告下方

java - jackson API : partially update a string

java - 是否可以从 AspectJ 编织中排除接口(interface)类

javascript - 在 Android 中,如何使用 Javascript 在 WebView 中设置编辑框的值