Calling activity method from FragmentPagerAdapter
我的
1 2 3 | public double getLatitude() { return this.latitude; } |
现在,我正在尝试在创建片段时将该值传递给片段(
1 2 3 4 5 6 7 8 9 10 11 12 13 | public Fragment getItem(int position) { if (position == 0) { return new Fragment1(); } else if (position == 1) { return new Fragment2(); } else { Fragment3 fragment3 = new Fragment3(); Bundle args = new Bundle(); args.putDouble(fragment3.ARG_PARAM1, getActivity().getLatitude()); fragment3.setArguments(args); return fragment3; } } |
号
但是,我得到一个编译错误,上面写着
在创建片段的新实例时,如何获取主要活动的
例子:
1 2 3 4 5 6 7 8 9 10 | class MainActivity extends Activity implements LatitudeProvider { // pager adapter creation new MyFragmentPagerAdapter(this); @Override public double getLatitude() { return this.latitude; } } |
碎片寻呼机适配器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | interface LatitudeProvider { double getLatitude(); } public class MyFragmentManagerAdapter extends FragmentPagerAdapter { private final LatitudeProvider latitudeProvider; public MyFragmentManagerAdapter(LatitudeProvider latitudeProvider) { this.latitudeProvider = latitudeProvider; } ... // Now you can get your latitude like this: latitudeProvider.getLatitude(); } |
。
为什么不在类似适配器的构造函数中传递该值
假设您的适配器类名是viewpagerpageradapter,然后在该适配器中执行以下操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class ViewPagerPagerAdapter extends FragmentPagerAdapter { private double mLattitude; public ViewPagerPagerAdapter (double lattitude) { this.mLattitude = lattitude; } //Now use that mLattitude wherever you want public Fragment getItem(int position) { if (position == 0) { return new Fragment1(); } else if (position == 1) { return new Fragment2(); } else { Fragment3 fragment3 = new Fragment3(); Bundle args = new Bundle(); args.putDouble(fragment3.ARG_PARAM1, mLattitude); Log.d("WHATEVER","WHATEVER:" + String.valueOf(mLattitude)); fragment3.setArguments(args); return fragment3; } } } |
现在,当您从
1 | ViewPagerAdapter adapter = new ViewPagerAdapter(lattitude); |
。
getActivity()返回上下文,而不是mainActivity的对象。据我所知,在android中没有办法获得当前的活动对象。所以您应该将其公开和静态,如下所示。
1 2 3 | public static double getLatitude() { return this.latitude; // make latitude public and static as well } |
现在在mainactivity.java中
1 | MainActivity.getLatitude(); |
号
如果值不变。然后您可以在构造函数中传递它。