【问题标题】:Dynamic Method with Fragments带片段的动态方法
【发布时间】:2017-04-05 00:44:06
【问题描述】:

我正在创建一个应用程序并使用 DrawerActivity。 这个 DrawerActivity 有 onNavigationItemSelected() 方法。 我的问题是,我可以创建一个类似的方法

public void select(Fragment fragment) {
    FragmentTransaction transaction = menuActivity.getSupportFragmentManager().beginTransaction();

    transaction.replace(R.id.fragment_container, fragment);
    transaction.addToBackStack(null);

    transaction.commit();
}

因此,我只会传递所需的 Fragment。过去我曾经有数百行代码,现在想改变它。如果您愿意,这是我希望创建的一种灵活方法。上面的例子不起作用,因为它需要一个明确的对象,但我希望你明白我的问题的重点。

感谢您的关注:)

【问题讨论】:

  • 不能简单的根据发送到onNavigationItemSelected()的id创建fragment实例并调用select方法吗?
  • 碎片很多,想减少代码

标签: java android object android-fragments methods


【解决方案1】:

您总是需要将每个菜单项 ID 映射到特定片段。

为了避免长的 switch case 语句,您可以使用 Abstract Factory Pattern 这样的设计模式和反射。

一些示例代码

public class FragmentFactory {
    private Map<Integer, Class<? extends Fragment>> menuItemFragments;

    public FragmentFactory() {
        menuItemFragments = new HashMap<>();
        menuItemFragments.put(R.id.fragment_main, MainFragment.class);
        menuItemFragments.put(R.id.fragment_about, AboutFragment.class);
        menuItemFragments.put(R.id.fragment_settings, SettingsFragment.class);
    }

    public Fragment getFragmentById(int menuItemId) {
        Class<? extends Fragment> fragmentClass = menuItemFragments.get(menuItemId);
        if(fragmentClass == null) throw new NullPointerException("fragment not found");
        try {
            return fragmentClass.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("failed to construct fragment", e);
        }
    }
}

比在 onNavigationItemSelected 中,您执行以下操作:

 private FragmentFactory mFragmentFactory = new FragmentFactory();

 public boolean onNavigationItemSelected(MenuItem menuItem) {
        Fragment fragment = mFragmentFactory.getFragmentById(menuItem.getItemId());
        select(fragment);

        return true;
 }

【讨论】:

  • 但是因此我总是需要知道片段在哈希图中的位置对吗?
  • 否,因为它与菜单项 id 映射。只需使用 getFragmentById 方法获取属于菜单项的片段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 1970-01-01
相关资源
最近更新 更多