英文:
Call method from Fragment in unselected tab
问题
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
String tag = "android:switcher:" + viewPager.getId() + ":" + viewPager.getCurrentItem();
Fragment f = getSupportFragmentManager().findFragmentByTag(tag);
((MyFragment) f).someMethod();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
String tag = "android:switcher:" + viewPager.getId() + ":" + tab.getPosition();
Fragment f = getSupportFragmentManager().findFragmentByTag(tag);
if (f != null) {
// Call the method on the unselected fragment
((MyFragment) f).someUnselectedMethod();
}
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
英文:
I have an application with tabs. I use ViewPager
and TabLayout
. In each tab I have a Fragment
. When the tab is unselected I want to call a method from the fragment in that tab.
If I want to call method on selected fragment i will do:
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
String tag = "android:switcher:" + viewPager.getId() + ":" + viewPager.getCurrentItem();
Fragment f = getSupportFragmentManager().findFragmentByTag(tag);
((MyFragment) f).someMethod();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
But the problem is, that I don't know how to do it on unselected tab.
Can you help me with this?
答案1
得分: 1
你可以尝试在onTabUnselected
方法中运行你的代码,但要注意这个片段可能会在下一步被销毁。
@Override
public void onTabUnselected(TabLayout.Tab tab) {
// 标记选项卡位置
String tag = "android:switcher:" + viewPager.getId() + ":" + tab.getPosition();
Fragment f = getSupportFragmentManager().findFragmentByTag(tag);
if (f instanceof MyFragment) {
((MyFragment) f).someMethodWhenUnselecting();
}
}
还要记住,ViewPager
仅在当前页和左右各保留一个Fragment
在内存中。所以,如果你从位置5
移动到位置4
,那么位置3
及以下的内容就不存在了。
英文:
you can try run your code in onTabUnselected
method, but be aware that this fragment may be destroyed in a next step.
@Override
public void onTabUnselected(TabLayout.Tab tab) {
// tag for tab position
String tag = "android:switcher:" + viewPager.getId() + ":" + tab.getPosition();
Fragment f = getSupportFragmentManager().findFragmentByTag(tag);
if(f instanceof MyFragment) {
((MyFragment) f).someMethodWhenUnselecting();
}
}
also remember that ViewPager
keeps in memory only current and one Fragment
to the left and one to the right of current. so if you moving from e.g. 5
position to 4
then position 3
and below aren't existing
pozdrowienia
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论