为了避免使用硬编码标记 f$id
set internally 寻找片段,这可能会在 Google 未来的版本中更改:
方法一:使用已恢复的页面片段过滤
假设 ViewPager2
的页面片段为 PageFragment
,那么您可以在当前的 fragmentManager fragments
中查找当前的 ViewPager
片段,并检查它是否处于已恢复状态(当前在屏幕上显示)。
val fragment = supportFragmentManager.fragments
.find{ it is PageFragment && it.isResumed } as PageFragment
注意:如果
ViewPager
是 Fragment 的一部分,则应将
supportFragmentManager
替换为
childFragmentManager
。
对于 Java(API 24+):
Fragment fragment =
getSupportFragmentManager().getFragments().stream()
.filter(it -> it instanceof PageFragment && it.isResumed())
.collect(Collectors.toList()).stream().findFirst().get();
方法二:将某些参数设置为PageFragment,并根据其过滤片段
Kotlin:
适配器
class MyAdapter(fragmentManager: FragmentManager, lifecycle: Lifecycle) :
FragmentStateAdapter(fragmentManager, lifecycle) {
override fun createFragment(position: Int): Fragment
= PageFragment.getInstance(position)
}
页面片段:
class PageFragment : Fragment() {
companion object {
const val POSITION = "POSITION";
fun getInstance(position: Int): PageFragment {
return PageFragment().apply {
arguments = Bundle().also {
it.putInt(POSITION, position)
}
}
}
}
}
使用位置参数进行过滤,以获取所需的PageFragment:
val fragment = supportFragmentManager.fragments.firstOrNull {
it is PageFragment && it.arguments?.getInt("POSITION") == id }
Java(API 24+):
适配器:
class MyAdapter extends FragmentStateAdapter {
@NonNull
@Override
public Fragment createFragment(int position) {
return PagerFragment.newInstance(position);
}
}
页面片段:
public class PagerFragment extends Fragment {
public static Fragment newInstance(int position) {
PagerFragment fragment = new PagerFragment();
Bundle args = new Bundle();
args.putInt("POSITION", position);
fragment.setArguments(args);
return fragment;
}
}
获取特定
viewPager
项的片段:
Optional<Fragment> optionalFragment = getSupportFragmentManager().getFragments()
.stream()
.filter(it -> it instanceof PagerFragment && it.getArguments() != null && it.getArguments().getInt("POSITION") == id)
.findFirst();
optionalFragment.ifPresent(fragment -> {
});
fragmentManager.findFragmentById(getItemId(index).toInt())
from within theFragmentStateAdapter
seems to work but only after the fragment has been added. From the docs this may not work though if the fragments are moved.Default implementation works for collections that don't add, move, remove items
- Markymark