gpt4 book ai didi

java - 从 ViewPager fragment 获取 Google map

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:05:23 26 4
gpt4 key购买 nike

我正在尝试从 Fragment 中获取 GoogleMap 对象,它位于 ViewPager 的第二页,其内容由FragmentPagerAdapter

我的 ViewPager 由两个页面组成:一个普通布局和一个 Google map 。

我可以访问第一个布局:

View tempView = LayoutInflater.from(getApplication())
.inflate(R.layout.start_activity, null);
tempTextView = (TextView) tempView.findViewById(R.id.timer);

这里一切正常。但我也想访问谷歌地图。
本地图处于单独的 Activity 中时,我可以获得 GoogleMap 对象执行此操作:

map=((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();

但是现在上面的行返回了null

问题是现在如何从 fragment 中获取GoogleMap对象?

他们建议这样做(有些人说这行得通),但对我不起作用:

map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentByTag("android:switcher:" + R.id.pager + ":1")).getMap();

我提供代码 here .

最佳答案

我找到了解决方案 here ,但也会在这里发布以供其他用户查看代码,而不会像我一样被卡住数周。

MyPagerAdapter.java

public class MyPagerAdapter extends FragmentPagerAdapter
{
private Context context;
final LatLng YEREVAN = new LatLng(40.181, 44.513);

public MyPagerAdapter(FragmentManager fm, Context context)
{
super(fm);
this.context = context;
}

@Override
public Fragment getItem(int position)
{
switch (position)
{
case 0:
return new MyFragment();
case 1:
return MyMapFragment.newInstance(YEREVAN);
}
return null;
}

@Override
public int getCount()
{
return 2;
}

@Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
switch (position)
{
case 0:
return context.getString(R.string.start).toUpperCase(l);
case 1:
return context.getString(R.string.map).toUpperCase(l);
}
return null;
}
}

MyMapFragment.java

public class MyMapFragment extends SupportMapFragment
{
private LatLng latLon;

public MyMapFragment()
{
super();
}

public static MyMapFragment newInstance(LatLng position)
{
MyMapFragment frag = new MyMapFragment();
frag.latLon = position;
return frag;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = super.onCreateView(inflater, container, savedInstanceState);
initMap();
return v;
}

private void initMap()
{
UiSettings settings = getMap().getUiSettings();
settings.setAllGesturesEnabled(false);
settings.setMyLocationButtonEnabled(false);

getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(latLon, 16));
getMap().addMarker(new MarkerOptions().position(latLon).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));
}
}

关于java - 从 ViewPager fragment 获取 Google map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15462259/

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