为什么getSupportFragmentManager()。findFragmentByTag在轮换后返回null?

时间:2017-02-07 21:24:50

标签: android android-fragments fragmentmanager

我正在尝试制作包含Activity和两个Fragments的应用。任何片段都可以调用由Activity实现的接口方法:

@Override
public void onFragmentRequest(final String fragmentTag) {

  new Thread(new Runnable() {
      @Override
      public void run() {
          try {
              // simulate network connection
              Thread.sleep(3000);
          } catch (InterruptedException e) {
              e.printStackTrace();
          }

          runOnUiThread(new Runnable() {
              @Override
              public void run() {
                Fragment fragment = getSupportFragmentManager()
                        .findFragmentByTag(fragmentTag);

                if(fragment == null)
                    Log.d(TAG, "fragment is null");
                else {
                    if(fragment instanceof OnFragmentResponse)
                        ((OnFragmentResponse) fragment).onFragmentResponse();
                }
              }
          });
      }
  }).start();

}

但问题是在致电onFragmentRequest并使设备轮换getSupportFragmentManager().findFragmentByTag(fragmentTag)后返回null

我替换所有片段并添加到后台堆栈,然后我调用commit方法和manager.executePendingTransactions(),但没有帮助

在轮换之前或之后记录:

02-07 16:39:12.202 29750-29750/com.testfrag3 D/MainActivity: onFragmentRequest: fragmentTag = NewsFragment
02-07 16:39:12.203 29750-29750/com.testfrag3 D/MainActivity: getSupportFragmentManager.entryCount = 1
02-07 16:39:12.203 29750-29750/com.testfrag3 D/NewsFragment: onFragmentResponse success

呼叫onFragmentRequest和设备轮换时记录:

02-07 16:39:23.454 29750-29750/com.testfrag3 D/MainActivity: onFragmentRequest: fragmentTag = NewsFragment
02-07 16:39:23.454 29750-29750/com.testfrag3 D/MainActivity: getSupportFragmentManager.entryCount = 1
02-07 16:39:23.454 29750-29750/com.testfrag3 D/MainActivity: fragment is null

1 个答案:

答案 0 :(得分:0)

试试这个:

getSupportFragmentManager().executePendingTranscation();