gpt4 book ai didi

java - 从 FragmentPagerAdapter 调用 Activity 方法

转载 作者:行者123 更新时间:2023-11-30 01:29:48 25 4
gpt4 key购买 nike

我的 MainActivity 有一个 double 纬度值,我想将它传递给 FragmentPagerAdapter 内的 fragment ,所以我创建了这个 getter 方法在 MainActivity.java 中:

public double getLatitude() {
return this.latitude;
}

现在我试图在创建 fragment 时将此值传递给 fragment (getItem() 方法是 FragmentPagerAdapter 类的一部分):

    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;
}
}

但是,我收到一个编译错误,提示 Error:(156, 68) error: cannot find symbol method getActivity()

当我创建 fragment 的新实例时,如何获取主要 Activity 的 getLatitude()

最佳答案

为什么不在 Adapter 的构造函数中传递该值

假设您的适配器类名称是 ViewPagerPagerAdapter 然后在该适配器中执行以下操作

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;
}
}
}

现在,当您从 MainActivity 启动适配器时,执行

ViewPagerAdapter adapter = new ViewPagerAdapter(lattitude);

关于java - 从 FragmentPagerAdapter 调用 Activity 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35921957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com