azi*_*ian 4 java android android-fragments android-viewpager google-maps-android-api-2
我正试图GoogleMap从a Fragment的第二页获取对象ViewPager,其内容是给出的FragmentPagerAdapter.
我ViewPager由两个页面组成:普通版面和Google地图.
我可以访问第一个布局:
View tempView = LayoutInflater.from(getApplication())
.inflate(R.layout.start_activity, null);
tempTextView = (TextView) tempView.findViewById(R.id.timer);
Run Code Online (Sandbox Code Playgroud)
这里一切都好.但我也想访问谷歌地图.
当地图在一个单独的活动中时,我可以让GoogleMap对象执行此操作:
map=((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
Run Code Online (Sandbox Code Playgroud)
但现在上面的线回来了 null
问题是如何GoogleMap从片段中获取对象?
他们建议这样做(有些人说这有效),但它对我不起作用:
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentByTag("android:switcher:" + R.id.pager + ":1")).getMap();
Run Code Online (Sandbox Code Playgroud)
我在这里提供代码.
我已经在这里找到了解决方案,但也会在这里发布,以便其他用户查看代码并且不会像我那样被困住数周.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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)));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2378 次 |
| 最近记录: |