我正在尝试在我的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
。
如何让它发挥作用?
答案 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
/ AppCompatActivity
,getSupportFragmentManager()
)。
答案 1 :(得分:-2)
使用支持库getSupportFragmentManager().beginTransaction().add(...).commit();