Android:Fragment!isDetached()和isAdded()之间有什么区别?

时间:2015-06-09 10:09:30

标签: android android-fragments

在我的片段中,我想在加载一些数据后制作Toast,如下所示:

  private class HomeFramgnet extends Fragment {
        private ProgressReceiver progressReceiver;
        Override

        public void onCreate(Bundle savedInstanceState) {
            progressReceiver = new ProgressReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(CheckNuevosAvisosIntentService.ACTION_PROGRESO);
            intentFilter.addAction(CheckNuevosAvisosIntentService.ACTION_FIN);
            registerReceiver(progressReceiver, intentFilter);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            unregisterReceiver(progressReceiver);;
        }

        class ProgressReceiver extends BroadcastReceiver {
            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                Log.e("Testing", "HomeFragment. BoradcastReceiver.  Dentro de onReceive");

                if (intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_PROGRESO)) {

                    Log.e("Testing", "HomeFragment. BoradcastReceiver. The service is running...");


                } else if (intent.getAction().equals(CheckNuevosAvisosIntentService.ACTION_FIN) && isAdded()) {
                    Log.e("Testing", "HomeFragment. BoradcastReceiver. The service has been ended");


                }

            }
        }
    }

只有片段仍然附加到Activity时才有意义,即Fragment可见且getActivity()不会返回null。

我可以使用Toast.makeText(getActivity(), R.string.toast_loading_done, Toast.LENGTH_SHORT).show(); !isDetached()查看,对吗?在这里,我想知道这两种方法之间的区别是什么,我应该优先使用哪种方法?

1 个答案:

答案 0 :(得分:13)

Fragment可以附加到Activity,而不会添加到其视图层次结构中。

如果分离了Fragment,则会保持状态,并且可以重新添加。