我的ViewPager的前两页总是相同的,因为切换到第一个元素(索引0)时不会调用适配器。所有其他片段都可以正常工作。使用getItem()
中的位置会返回完全奇怪的位置,因此我使用的是ViewPager的getCurrentItem()
方法。
TimetableActivity:
public class TimetableActivity extends FragmentActivity {
private ViewPager mPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen_slide);
ActionBar actionBar = getActionBar();
actionBar.setTitle("Stundenplan");
actionBar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
mPager = (ViewPager) findViewById(R.id.pager);
PagerAdapter mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager(), mPager);
mPager.setAdapter(mPagerAdapter);
}
@Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
} else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}}
ScreenSlidePagerAdapter:
public class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
private ViewPager pager;
public ScreenSlidePagerAdapter(FragmentManager fm, ViewPager pager) {
super(fm);
this.pager = pager;
}
@Override
public Fragment getItem(int position) {
System.out.println("Current Item: " + pager.getCurrentItem());
return ScreenSlidePageFragment.newInstance(pager.getCurrentItem());
}
@Override
public int getCount() {
return 10;
}}
ScreenSlidePageFragment:
public class ScreenSlidePageFragment extends Fragment {
private List<TableRow> rows;
private int position;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.activity_timetable, container, false);
return rootView;
}
public static ScreenSlidePageFragment newInstance(int num) {
ScreenSlidePageFragment f = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt("position", num);
f.setArguments(args);
return f;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("Called");
ActionBar actionBar = getActivity().getActionBar();
position = getArguments() != null ? getArguments().getInt("position") : 1;
System.out.println(position);
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
Calendar c = Calendar.getInstance();
if (position == 5) {
actionBar.setTitle("Stundenplan (" + format.format(c.getTime()) + ")");
} else if (position < 5) {
int daysBack = 5 - position;
c.add(Calendar.DAY_OF_MONTH, daysBack * -1);
actionBar.setTitle("Stundenplan (" + format.format(c.getTime()) + ")");
} else {
int daysForward = position - 5;
c.add(Calendar.DAY_OF_MONTH, daysForward);
actionBar.setTitle("Stundenplan (" + format.format(c.getTime()) + ")");
}
}}
所以问题是getCurrentItem()
似乎永远不会是0。
任何人都可以帮助我吗?
答案 0 :(得分:0)
你怎么知道getCurrentItem不是0,你在调试中看过它的值还是注意到按下后活动还没有完成?因为如果它是第二选择你需要知道FragmentActivity onBackPressed()会弹出片段backstack,直到它为空,然后才结束活动。所以你可能想直接调用finish()而不是super.onBackPressed()。