gpt4 book ai didi

android - SupportFragmentManager 的 findFragmentById 始终返回 null

转载 作者:行者123 更新时间:2023-11-29 14:46:37 26 4
gpt4 key购买 nike

我正在尝试使用 findFragmentById() 获取 fragment 引用,但它总是返回空对象。我使用了 FragmentPagerAdapter 并附加了一个 OnPageChangeListener 这样每当我滚动到一个特定的 Fragment 时,比如 FragmentBFragmentB< 的一个方法 应该被解雇。

我有以下代码:

mPager.addOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
if (position == 1) {
FragmentB fb = (FragmentB) getSupportFragmentManager().findFragmentById(R.id.fragment_b);

fb.refreshList();
//fb is always null

Toast.makeText(MainActivity.this,"Scrolled", Toast.LENGTH_SHORT).show();
//Toast is working fine
}
}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2){}

@Override
public void onPageScrollStateChanged(int arg0){}
});

最佳答案

只需这样做:

mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
PagerAdapter pagerAdapter = (PagerAdapter) mPager.getAdapter();
if (position == 1) {
FragmentB fragmentB = (FragmentB)pagerAdapter.getItem(position);
fragmentB.refreshList();
}
}

@Override
public void onPageSelected(int position) {}

@Override
public void onPageScrollStateChanged(int state) {}
});

findFragmentById的问题不打算这样用:

Finds a fragment that was identified by the given id either when inflated from XML or as the container ID when added in a transaction. This first searches through fragments that are currently added to the manager's activity; if no such fragment is found, then all fragments currently on the back stack associated with this ID are searched.

在使用 时,您应该调用它来获取 fragment 容器中的哪个 fragment (例如,如果您正在使用 Navigation Drawer 并且想知道哪个 fragment 在视口(viewport)中) ViewPager,托管多个 fragment 。

希望对您有所帮助。

关于android - SupportFragmentManager 的 findFragmentById 始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34752990/

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