如何在片段中使用mapfragment

问题描述 投票:1回答:3

主要是我有一个带有下拉菜单的FragmentActivity,一旦你从该菜单中选择一个项目,它就会使我的私有类扩展Fragment以显示每次在地图上的其他东西它自己现在的问题是,当我在控制地图的片段类:

GoogleMap map = ((MapFragment)getFragmentManager.findFragmentById(R.id.map)).getMap()

它说您无法将片段转换为MapFragment,所以我尝试为该类扩展MapFragment,但是当我在下拉菜单中选择一个项目时,我会执行以下代码:

Fragment fragment = new MyFragmentClass()();
Bundle args = new Bundle();
args.putInt(PlacesFinder.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();

我只能使用片段,所以如果我不能在片段类中查找它并且因为下拉菜单而无法扩展mapfragment,我怎么能在片段内使用谷歌地图?

谢谢你抬头:)

android fragment google-maps-android-api-2 mapfragment
3个回答
0
投票

你可以在片段中使用GoogleMap。仅查看在XML中创建片段的代码部分,就会出现错误。假设这个片段是XML布局中唯一的元素,那么应该如何阅读:

<fragment xmlns:android="schemas.android.com/apk/res/android" 
    android:id="@+id/map" 
    android:layout_width="match_parent"      
    android:layout_height="match_parent"  
    class="com.google.android.gms.maps.MapFragment"/>

你的XML的最后一行,你有android:name是错误的。您在活动中添加地图的代码应该有效

GoogleMap map = ((MapFragment)getFragmentManager.findFragmentById(R.id.map)).getMap();

我以前使用过这段代码没有问题

mapFrag = ((SupportMapFragment) getFragmenManager().findFragmenById(R.id.map)).getMap();

唯一的区别是(1)我使用的是SupportMapFragment; (2)我在GoogleMap之外宣布我的onCreate

这听起来是基于你所描述的那些片段无法被转换为正确的类,这是一个问题,或者是片段XML中的错误,或者你没有使用正确的导入。如果你正在使用MapFragment,那么你需要确保你使用MapFragment导入(不是SupportMapFragment或只是Fragment)。

至于你的代码的最后一部分,我不确定与下拉菜单的关系是什么。看起来你正在将参数传递给片段?如果您能提供更多详细信息,我也会对此发表评论。


0
投票

抱歉延迟但这是主要活动:

public class MainActivity extends FragmentActivity implements
    ActionBar.OnNavigationListener , LocationListener{
    private String [] types;
    private ActionBar actionBar;

    public static GoogleMap map = null;
    public static boolean googlePlayOn = false;
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        types = getResources().getStringArray(R.array.values);
        googlePlayOn = isGooglePlay();
        actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

        // Set up the dropdown list navigation in the action bar.
        actionBar.setListNavigationCallbacks(
        // Specify a SpinnerAdapter to populate the dropdown list.
                new ArrayAdapter<String>(getActionBarThemedContextCompat(),android.R.layout.simple_list_item_1,android.R.id.text1, types), this);
    }

    /**
     * This function checks in the phone operating system that 
     * the phone got google play services
     * @return
     */
    private boolean isGooglePlay()
    {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if(status == ConnectionResult.SUCCESS)
            return true;
        else
            ((Dialog) GooglePlayServicesUtil.getErrorDialog(status, this, 10)).show();
        return false;
    }


    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private Context getActionBarThemedContextCompat() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            return getActionBar().getThemedContext();
        } else {
            return this;
        }
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Restore the previously serialized current dropdown position.
        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
            getActionBar().setSelectedNavigationItem(
                    savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Serialize the current dropdown position.
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
                .getSelectedNavigationIndex());
    }


    @Override
    public boolean onNavigationItemSelected(int position, long id) {
        // When the given dropdown item is selected, show its contents in the
        // container view.
        if(position != PlacesFinder.currentTitle)
        {
            if(!PlacesFinder.created)
            {
                PlacesFinder.created = true;
                Bundle b = new Bundle();
                b.putInt(PlacesFinder.ARG_SECTION_NUMBER, position);
                Fragment fragment = new PlacesFinder();
                fragment.setArguments(b);
                getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
            }
            PlacesFinder.newTitleBeenChosenHandler.sendEmptyMessage(0);
        }
        return true;
    }



    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class PlacesFinder extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static boolean created = false;
        public static final String ARG_SECTION_NUMBER = "section_number";
        public static Handler newTitleBeenChosenHandler;
        public static int currentTitle = 0;
        private Context context;
        public PlacesFinder() {
            this.context = getActivity();
            loadMapFragment();
        }
        private void loadMapFragment()
        {
            if(googlePlayOn)
            {
                if(map == null)
                    map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

            }
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.places_fragment, container , false);
        }


    }



    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

}




This is the main xml file :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame" />

这是mapfragment文件:

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"/>

一旦我做了代码行map =((SupportMapFragment)getFragmentManager()。findFragmentById(R.id.map))。getMap();

应用程序失败,它说我有一个空指针,我不知道为什么...


0
投票

您应该使用getSupportFragmentManager()。

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

当您使用FragmentActivity时,这应该可行。我面临着同样的问题,虽然我正在使用片段而且不会这样做:(

© www.soinside.com 2019 - 2024. All rights reserved.