片段v4中的getPosition

时间:2014-08-25 20:02:28

标签: android android-fragments android-viewpager android-support-library

我使用android.support.v4.app.Fragment并在我的Fragment子类中,我想得到片段位置,如:

public abstract class MyFragment extends Fragment {

   public void process () {
      .....
      getPosition();

问题是Android中没有任何getPosition等效函数。如何获得该位置(与下面的片段相同)?

public class MyPageAdapter extends FragmentPagerAdapter {

     public Fragment getItem(int position) {
         .....

1 个答案:

答案 0 :(得分:4)

当您从PagerAdapter创建片段时,您可以将该位置作为参数传递给您的片段:

public class MyPageAdapter extends FragmentPagerAdapter {

     public Fragment getItem(int position) {
         return MyFragment.newInstance(position);
     }
     //...
}

public class MyFragment extends Fragment {

  int position;

  public static MyFragment newInstance(int position) {
    MyFragment f = new MyFragment();
    Bundle args = new Bundle();
    args.putInt("Position", position);
    f.setArguments(args);
    return f;
  }

  public void onCreate(Bundle savedInstanceState) {
    position = getArguments().getInt("Position");
  }
}