我的應用程序由標籤佈局組成,每個標籤都有自己的片段。我從來沒有遇到需要「片段容器」,直到我需要刷新當前片段時,其父母AppCompatActivity
單擊後退按鈕。我在哪裏獲取片段容器的資源ID?
這裏是我當我想刷新片段代碼:
GlobalFeedTab fragment = (GlobalFeedTab)
getFragmentManager().findFragmentById(R.id.fragment_container);
getFragmentManager().beginTransaction()
.detach(fragment)
.attach(fragment)
.commit();
PageAdapter:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mTabs;
public PagerAdapter(FragmentManager fm, int tabs) {
super(fm);
this.mTabs = tabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
GlobalFeedTab tab1 = new GlobalFeedTab();
return tab1;
case 1:
CountryFeedTab tab2 = new CountryFeedTab();
return tab2;
case 2:
CountryList tab3 = new CountryList();
return tab3;
case 3:
NotificationsTab tab4 = new NotificationsTab();
return tab4;
case 4:
ProfileTab tab5 = new ProfileTab();
return tab5;
default:
return null;
}
}
@Override
public int getCount() {
return mTabs;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.earthicon));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.flagicon));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.listicon));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.notificationsiconi));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.profileicon));
// tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
當我開始輸入'FragmentManager.' ....'findFragmentByTag()'不會彈出@ pdegand59 – grant
什麼是一個容器,我怎麼引用它。我只需要它刷新當前片段 – grant
該方法不是靜態的,你必須做'getFragmentManager()。findFragmentByTag()' – pdegand59