Mapview片段类型不匹配错误

时间:2018-02-11 17:19:24

标签: java android

我正在尝试define一个mapview的片段。 我的xml文件是:

fragment_first.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <!--android:background="@android:color/holo_orange_dark" >-->

    <fragment xmlns:android="http://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.SupportMapFragment" />
</RelativeLayout>

并且java代码为:

FirstFragment.java (从google&#39; repo复制)

public class FirstFragment extends FragmentActivity
        implements OnMapReadyCallback {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_first);

        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we
     * just add a marker near Africa.
     */
    @Override
    public void onMapReady(GoogleMap map) {
        map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }
}

现在,我将此片段称为 MainActivity

public class MainActivity extends AppCompatActivity{
 ...
    private class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int pos) {
            switch (pos) {

                case 0:
                    return FirstFragment.onMapReady();

                default:
                    return ThirdFragment.newInstance("ThirdFragment, Default");
            }
        }

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

这给了我编译时错误:

  

错误:(105,41)错误:类FirstFragment中的onMapReady方法不能   适用于给定类型;要求:GoogleMap找到:没有参数   原因:实际和正式的参数列表长度不同

我在这里出错了什么?关于活动的论证,其中一部分是显而易见的,我仍然需要弄清楚。但是错误是什么:

  

非静态方法OnMapReady(...)无法从静态引用   上下文

请帮助。

1 个答案:

答案 0 :(得分:0)

  

非静态方法无法从静态上下文引用OnMapReady(...)

你需要使用 FirstFragment 的对象来调用它的方法 onMapReady(),因为 onMapReady()是非静态的。