我有以下代码,这是一个带有片段的标签布局。我想摆脱tab / pager并只保留1个片段(StickyQuestionDetailsFragment)并让它显示活动的整个宽度和高度。
我尝试从我的活动中打开片段,但是我得到了一个转换异常。
public class QuestionDetails extends SherlockFragmentActivity implements ActionBar.TabListener {
ViewPager mPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question_details);
PagerAdapter adapter = new FragmentStatePagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
switch (position) {
case 1:
return new QuickReturnFragment();
case 0:
return new StickyQuestionDetailsFragment();
}
return null;
}
@Override
public int getCount() {
return 1;//2
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Question";
case 1:
return "User";
}
return null;
}
};
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(adapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
getActionBar().setSelectedNavigationItem(position);
}
});
mPager.setPageMargin(getResources().getDimensionPixelSize(R.dimen.page_margin));
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int position = 0; position < adapter.getCount(); position++) {
getActionBar().addTab(getActionBar().newTab()
.setText(adapter.getPageTitle(position))
.setTabListener(this));
}
getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayShowTitleEnabled(false);
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
}
答案 0 :(得分:1)
如果每个活动只需要单个片段,则可以使用此模式(source):
public class QuestionDetails extends SherlockFragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// If not already added to the Fragment manager add it. If you don't do this a new Fragment will be added every time this method is called (Such as on orientation change)
if(savedInstanceState == null)
getSupportFragmentManager().beginTransaction().add(android.R.id.content, new StickyQuestionDetailsFragment()).commit();
}
}