新的LifecycleFragment组件和旧的FragmentTransaction

时间:2017-06-29 15:32:25

标签: android android-fragments

我正在尝试在我的Android应用程序中应用新的LifecycleFragment

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragmentContainer, new CustomBlockUrlProviderFragment());
        fragmentTransaction.addToBackStack("manage_custom_url_providers");
        fragmentTransaction.commit();

fragmentTransaction.replace(R.id.fragmentContainer, new CustomBlockUrlProviderFragment());我在这一行上遇到错误。说第二个参数应该是Fragment

如何让它发挥作用?

2 个答案:

答案 0 :(得分:8)

鉴于您的代码段的第一行,我猜您正在使用android.app.FragmentManager,而且历史上您一直在使用本机片段(android.app.Fragment)。 LifecycleFragment继承自片段backport(android.support.v4.app.Fragment),并且您无法在同一活动中混合并匹配本机和反向片段。

您可以创建自己的LifecycleFragment

import android.app.Fragment;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.LifecycleRegistry;
import android.os.Bundle;
import android.support.annotation.Nullable;

public class LifecycleFragment extends Fragment
  implements LifecycleOwner {
  private LifecycleRegistry registry=new LifecycleRegistry(this);

  @Override
  public Lifecycle getLifecycle() {
    return(registry);
  }

  @Override
  public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    registry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
  }

  @Override
  public void onStart() {
    super.onStart();

    registry.handleLifecycleEvent(Lifecycle.Event.ON_START);
  }

  @Override
  public void onResume() {
    super.onResume();

    registry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
  }

  @Override
  public void onPause() {
    super.onPause();

    registry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
  }

  @Override
  public void onStop() {
    super.onStop();

    registry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();

    registry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
  }
}

或者,切换到片段backport(例如,FragmentActivity / LifecycleActivity / AppCompatActivitygetSupportFragmentManager())。

答案 1 :(得分:-2)

使用支持库getSupportFragmentManager().beginTransaction().add(...).commit();

中的片段管理器