【发布时间】:2015-06-19 04:42:52
【问题描述】:
我正在尝试使用 UIless 保留 Fragment 在方向更改期间不丢失服务绑定器。问题是在onCreate Activity 中findFragmentByTag 总是返回null。
这是我的活动:
public abstract class AbstractLearnActivity extends Activity implements FragmentCallbacks {
private final static String BINDER_FRAG_TAG = "AbstractLearnActivity.BINDER_FRAG_TAG";
private BinderFragment binderFragment;
@Override
protected void onCreate(Bundle savedInstanceState){
FragmentManager fm = getFragmentManager();
//do some initialization stuff...
Fragment fragment = fm.findFragmentByTag(BINDER_FRAG_TAG);
if(fragment != null){
Log.i("asd", "Binder Frag already exists");
binderFragment = (BinderFragment)fragment;
}
else{
Log.i("asd", "Binder frag is null");
binderFragment = new BinderFragment();
fm.beginTransaction().add(binderFragment, BINDER_FRAG_TAG).commit();
}
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
}
}
虽然这是片段:
public class BinderFragment extends Fragment {
private Application application;
public BinderFragment(){
Log.i("asd", "Constructor called for binder fragment");
}
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
if(application == null){
application = activity.getApplication();
//make connections...
}
}
@Override
public void onCreate(Bundle savedInstanceState){
setRetainInstance(true);
super.onCreate(savedInstanceState);
}
@Override
public void onDestroy(){
Log.i("asd", "binder fragment destroyed");
super.onDestroy();
//disconnect services
}
}
如果我运行应用程序并尝试改变我得到的方向:
<application started>
I/asd﹕ Binder frag is null
I/asd﹕ Constructor called for binder fragment
I/asd﹕ Attaching
<orientation change>
I/asd﹕ Is fragment found? true
I/asd﹕ Binder frag is null
I/asd﹕ Constructor called for binder fragment
I/asd﹕ Attaching
<orientation change>
I/asd﹕ Is fragment found? true
I/asd﹕ Binder frag is null
I/asd﹕ Constructor called for binder fragment
I/asd﹕ Attaching
<application closed>
I/asd﹕ binder fragment destroyed
I/asd﹕ binder fragment destroyed
I/asd﹕ binder fragment destroyed
I/asd﹕ Is fragment found? false
正如您所见,Fragment 在 Activity 被销毁时就在那里,并且它被正确保留(因为它们在应用程序关闭时都被销毁),但是 onCreate 找不到它并创建一个新的.. . 有人知道为什么我不能按标签检索片段吗?
感谢您的帮助^^
【问题讨论】: