Fragment.iFyres()在support-v4:23.4.0中的行为与以前的版本不同

和尼科尔斯

当我将support-v4版本从23.1.1升级到23.4.0时,我注意到了这个问题:基本上,在我返回以前为true的情况下,iwego()总是返回false。

我有一个活动(FragmentActivity),它具有一个包含分片的ViewPager。每个片段在启动时都会在onCreate()中启动一个异步任务,以下载一些图像;为了提高效率,在回调中,我在继续处理之前检查iFyreed()以确保Fragment已附加。

如果我包含support-v4库的23.1.1版,则我的代码将按预期工作。但是,当我更新到23.4.0时,iFyreed()似乎几乎总是返回false,这甚至不允许当前片段完成对异步结果的处理。

注意:我是否翻阅相册都没关系-每次对iFyreed()的调用似乎都返回false。

以下相关代码(请注意:此示例简化了一些代码):

 // note FetchableListener implements onFetchableUpdate()
 public class CameraAlbumItemFragment
   implements Fetchable.FetchableListener
 {
    private static final String CAMERA_ALBUM_ITEM_FRAGMENT_CAMERA_KEY = "camera" ;

    // Member Variables
    //
    @Nullable private Camera m_camera ;
    @Nullable private ArrayList<CameraViewImageDownloadResult> m_imageDownloads;

    public static CameraAlbumItemFragment newInstance ( @NotNull Camera camera )
    {
       final CameraAlbumItemFragment fragment = new CameraAlbumItemFragment();
       fragment.setRetainInstance( true );

       final Bundle bundle = new Bundle( 1 );
       bundle.putParcelable( CAMERA_ALBUM_ITEM_FRAGMENT_CAMERA_KEY, camera );

       fragment.setArguments( bundle );

       return fragment;
    }

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

       m_camera = getArguments().getParcelable( CAMERA_ALBUM_ITEM_FRAGMENT_CAMERA_KEY );

      // If the images have not been downloaded, then start background
      // tasks to retrieve them. Not likely, but make sure our camera is not null
      //
      if ( m_camera != null && m_imageDownloads == null )
      {
          // This will start an async task that will call onFetchableUpdate() when it receives a response from the server
          m_camera.updateNonCurrentViews( getActivity(), this );
      }
   }

   /** The Fragment's UI */
   @Override
   public View onCreateView ( @NotNull LayoutInflater inflater,
                              @Nullable ViewGroup container,
                              @Nullable Bundle savedInstanceState )
   {
      final View view = inflater.inflate( R.layout.camera_album_item, container, false );

      // Set image if already downloaded
      //
      // Set the on click listener for the cycle image button
      // This has to be done here instead of using the android:onClick attribute in the layout
      // file because this is a fragment, not an activity
      //
      final ImageView cameraImageView = (ImageView) view.findViewById( R.id.camera_image_view );

      return view;
   }

   /**
    * Add an image to the list of downloaded images. Display or hide the cycle images button based on
    * the number of retrieved images
    *
    * @param bitmap An image retrieved by a background process
    */
   public void addImage ( @Nullable final Bitmap bitmap, @NotNull final String viewName )
   {
      assert m_imageDownloads != null;
      m_imageDownloads.add( new CameraViewImageDownloadResult( bitmap, viewName ) );
   }

   @Override
   public void onFetchableUpdate ( @NotNull Fetchable fetchable, @Nullable Object data )
   {
       //*********************************************************
       // NOTE: It is the call here to isAdded() that is returning false nearly 
       //       every time in support-v4:23.4.0 but not in 23.1.1
       //**********************************************************
      if ( fetchable == m_camera && isAdded() )
      {
         final List<CameraView> cameraViews = m_camera.getViews();
         m_imageDownloads = new ArrayList<>( cameraViews.size() );

         // Download camera images
         for ( CameraView cameraView : cameraViews )
         {
            if ( cameraView.isCurrent() )
            {
               final String imageURL = cameraView.getCameraURL();

               if ( imageURL != null )
               {
                  new GetCameraImageAsyncTask( this, cameraView.getName() ).execute( imageURL );
               }
               else
               {
                  Log.e( LOG_TAG, "No valid image URL for " + cameraView.getName() ) ;
                  addImage( null, cameraView.getName() );
               }
            }
            else
            {
               addImage( null, cameraView.getName() );
            }
         }

         // We don't need to maintain the observer reference anymore
         m_camera.removeListener( this );
      }
   }

   /**
    * Get the image view for displaying a camera view
    *
    * @return The camera image view
    */
   @Nullable
   private ImageView getCameraImageView ()
   {
      final View v = getView();
      if ( v != null )
      {
         return (ImageView)v.findViewById( R.id.camera_image_view );
      }
      else
      {
         return null;
      }
   }
}

及其包含ViewPager的Activity(FragmentActivity)

 public class CameraAlbumActivity
    extends FragmentActivity
 {
    // Intent Data Key
    //
    public final static String CAMERA_ALBUM_SELECTED_ID_KEY = "selectedId" ;

     private static final String LOG_TAG = "CameraAlbumActivity" ;

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

       final Intent intent = getIntent();

       final Object sharedData = SharedDataWrapper.getInstance().getData();

        CameraCollection cameraCollection ;

        if ( sharedData != null && sharedData instanceof CameraCollection )
        {
            cameraCollection = ( CameraCollection ) sharedData;
        }
        else
        {
            // just create an empty collection
            cameraCollection = new CameraCollection() ;
        }

        // Load view
        setContentView( R.layout.album );

        // Get references to buttons
        //
        m_previousButton = (ImageView)findViewById( R.id.album_previous_btn );
        m_nextButton = (ImageView)findViewById( R.id.album_next_btn );

        // Configure view pager
        //
        m_viewPager = (ViewPager)findViewById( R.id.album_view_pager );

       final CameraAlbumPagerAdapter adapter = new CameraAlbumPagerAdapter( getSupportFragmentManager(), cameraCollection );
       m_viewPager.setAdapter( adapter );
       m_viewPager.addOnPageChangeListener( new OnCyclingContentAlbumViewScrollListener( this, adapter ) );

       // Set the selected item
       int selectedId = intent.getIntExtra( CAMERA_ALBUM_SELECTED_ID_KEY, -1 );
       if( selectedId == -1 )
       {
          return;
       }

       List<Camera> models = cameraCollection.getAllModels();

       for ( int i = 0 ; i < models.size() ; i++ )
       {
           Camera camera = models.get( i );
           if ( selectedId == camera.getId() )
           {
               m_viewPager.setCurrentItem( i, false );
               break;
           }
       }
    }

     /**
      * OnPageChangeListeners should be removed to prevent memory leaks
      */
     @Override
     public void onDestroy()
     {
         m_viewPager.clearOnPageChangeListeners() ;

         super.onDestroy() ;
     }

     /**
      * Scroll one item to the right, if possible
      *
      * @param v the view triggering the event
      */
     public void scrollToNext ( @SuppressWarnings("UnusedParameters") View v )
     {
        int currentIndex = m_viewPager.getCurrentItem();

        if( currentIndex < m_viewPager.getAdapter().getCount() - 1 )
        {
           m_viewPager.setCurrentItem( currentIndex + 1, true );
        }
     }

     /**
      * Scroll one item to the left, if possible
      *
      * @param v the view triggering the event
      */
     public void scrollToPrevious ( @SuppressWarnings("UnusedParameters") View v )
     {
        int currentIndex = m_viewPager.getCurrentItem();

        if( currentIndex > 0 )
        {
           m_viewPager.setCurrentItem( currentIndex - 1, true );
        }
     }

     /**
      * Set the visibility of the previous and next buttons based on view pager contents and position
      */
     public void setPreviousAndNextButtonVisibility ()
     {
        final int position = m_viewPager.getCurrentItem();

        m_previousButton.setVisibility( position == 0 ? View.INVISIBLE : View.VISIBLE );
        m_nextButton.setVisibility( position < m_viewPager.getAdapter().getCount() - 1 ? View.VISIBLE : View.INVISIBLE );
     }

     /**
      * @return The item fragment which is currently displayed
      */
     @Nullable
     public Fragment getCurrentItemFragment ()
     {
        int currentItem = m_viewPager.getCurrentItem();
        ModelCollectionAlbumPagerAdapter adapter = (ModelCollectionAlbumPagerAdapter)m_viewPager.getAdapter();
        return adapter.getRegisteredFragment( currentItem );
     }

 }

我不确定这个版本的支持库是否有问题(希望如此),或者我的代码中有什么不正确的问题最终会在最新版本中浮出水面。正如我提到的,如果我只是在gradle文件中交换版本,则上面的代码在v 23.1.1中可以按预期工作,但是当我更改为23.4.0时,它将失败。

有什么想法吗?有什么建议吗?

谢谢!

和尼科尔斯

经过进一步调查,对支持库的更新显示了现有代码中的缺陷。请注意,异步任务的开始从onCreate()开始。如果异步任务要在onCreateView()完成之前完成,则当前Fragment.iwego()调用将返回false。

无论出于何种原因,在较旧的支持库中都不会发生这种情况(或者,如果这样,那么我很少会观察不到)。新支持库的更新相当一致地触发了这种情况。

解决方法是将异步任务的开始移到onActivityCreated()中,当然,在添加Fragment之后会调用它。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

android.support.v4.app.Fragment中的MapView

使用backstack时android.app.Fragment和android.support.v4.app.Fragment的不同行为

App.Fragment和V4.support.fragment中的地图

无法解析android.support.v4.app.Fragment(版本21.0.3)Android Studio中的方法getContext()

typeanumber中的错误-无法解决android.support.v4.app.fragment

无法转换为android.support.v4.app.Fragment

找不到android.support.v4.fragment的fragmentclass文件

android.support.v4.app.Fragment的缺点

setTargetFragment for android.support.v4.app.Fragment?

Android Studio android.support.v4.app.Fragment'

android.app.Fragment和android.support.v4.app.Fragment之间的区别

子模块目录中的Android Support V4断开链接

不同的布局-React Router v4

Ionic v4中的事件

滑行v4中的FifoPriorityThreadPoolExecutor

botframework v4 中的调用响应

在MySQL中存储UUID v4

在Bootstrap v4中抵消列

React Router v4中的indexLink

Ionic V4中的Deeplink?

Antlr v4中的值匹配

为什么AdnroidInjector.inject(fragment)使用不推荐使用的android.support.v4.app.Fragment

多个dex文件定义了Landroid / support / v4 /

NoClassDefFoundError android / support / v4 / animation / AnimatorCompatHelper

为什么在android.support.v4.app.Fragment.setTargetFragment期间出现java.lang.IllegalArgumentException

在 PreferenceFragment 和 android.support.v4.app.Fragment 之间切换;

在空对象引用上无效android.support.v4.app.Fragment.setMenuVisibility(boolean)'

错误:无法将MapFragment强制转换为android.support.v4.app.Fragment

错误的第二个参数类型。需要:'android.support.v4.app.Fragment'