gpt4 book ai didi

android - Dagger 回收 View 布局管理器注入(inject)

转载 作者:行者123 更新时间:2023-11-29 15:37:35 24 4
gpt4 key购买 nike

我正在尝试使用 fragment 中的 Dagger 注入(inject) recyclerview layoutmanager,问题是当我返回到包含该注入(inject)的 fragment 时,我得到了一个错误,导致 layoutmanager 已经被另一个 recyclerview 使用。实际上离开 fragment 会破坏 fragment View 并返回它只重新创建 fragment View 而不是 fragment 实例本身所以布局管理器注入(inject)仍然是同一个实例。这是我的代码,可以使事情更清楚:

来自 Activity 模块:

@PerFragment
@ContributesAndroidInjector( modules = ProductListFragmentModule.class )
abstract ProductListFragment contributeProductListFragment( );

ProductListFragmentModule Dagger 模块

@Provides
@PerFragment
public static RecyclerView.LayoutManager provideProductListLayoutManager(
@ActivityContext Context context,
FlexibleAdapter< AbstractFlexibleItem< ? extends BaseViewHolder > > flexibleAdapter )
{
int totalSpanSize = 6;
GridLayoutManager gridLayoutManager = new GridLayoutManager( context,
totalSpanSize,
LinearLayoutManager.VERTICAL,
false );

gridLayoutManager.setSpanSizeLookup( new GridLayoutManager.SpanSizeLookup( )
{
@Override
public int getSpanSize( int position )
{
IFlexible item = flexibleAdapter.getItem( position );

if( item != null && item instanceof GridLayoutItem )
return ( ( GridLayoutItem ) item ).getSpanSize( totalSpanSize );

return totalSpanSize;
}
} );

return gridLayoutManager;
}

来自 ProductListFragment 类:

@BindView( R.id.list )
RecyclerView mList;
@Inject
RecyclerView.LayoutManager mLayoutManager;

...


@Override
public void onActivityCreated( @Nullable Bundle savedInstanceState )
{
mList.setLayoutManager( mLayoutManager );
}

所以正如我所说,第一次创建 fragment 没问题,但是当离开 fragment 并返回(使用 backstack)时,出现关于布局管理器已经附加到回收 View 的错误。

我想保留 layoutmanager 注入(inject)并避免从我的 fragment 中创建实例,无论如何都可以这样做吗?我正在考虑为每个 fragment View 设置一个 Dagger 范围以及每个 Activity/每个 fragment 范围的标准范围,但无法弄清楚如何做到这一点。

感谢任何建议。

最佳答案

我在向 ViewPager 中的 fragment 注入(inject)时遇到了类似的问题。对我有用的解决方案之一可能适用于您的情况。

从模块中删除 @PerFragment 注释以确保在请求时创建 LayoutManager 的新实例:

@Provides
public static RecyclerView.LayoutManager provideProductListLayoutManager() {...}

注入(inject) RecyclerView.LayoutManager 的提供者而不是实例:

@Inject
Provider<RecyclerView.LayoutManager> mLayoutManager;

每次附加 fragment 时使用提供程序实例化布局管理器:

mList.setLayoutManager(mLayoutManager.get());

我在使用 ViewPager 时遇到的问题通过使用 FragmentStatePagerAdapter instaed of FragmentPagerAdapter 简单地解决了

这归结为没有缓存 fragment 实例并确保每个 fragment 生命周期仅调用一次 onCreateView。

关于android - Dagger 回收 View 布局管理器注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46757168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com