从活动中调用mapfragment

时间:2018-02-12 14:13:04

标签: android google-maps-android-api-2

我已将GoogleMap定义为:

fragment.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">

    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    </RelativeLayout>

fragment.java

public class SecondFragment extends Fragment implements onMapReadyCallback {

    private GoogleMap mMap;

    public static SecondFragment newInstance() {
        SecondFragment fragment = new SecondFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_maps, null, false);

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

        return view;
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }
}

我的主要活动是:

import android.content.pm.PackageManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

import com.google.android.gms.maps.GoogleMap;


public class MainActivity extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
        pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        //mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        //mViewPager = (ViewPager) findViewById(R.id.container);
        //mViewPager.setAdapter(mSectionsPagerAdapter);

        //Get Location Permission
        if (ContextCompat.checkSelfPermission(getApplicationContext(),
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(getApplicationContext(),
                        android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]
                    {android.Manifest.permission.ACCESS_FINE_LOCATION,
                            android.Manifest.permission.ACCESS_COARSE_LOCATION}, 101);

        }

        // Tab to get Date TODO: Expand fo both Location and Date
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDateDialog();
            }
        });

    }

    public void showDateDialog() {
        DialogFragment CalFragment = new CalFragment();
        CalFragment.show(getSupportFragmentManager(), "timePicker");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {

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


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

                case 0:
                    return FirstFragment.newInstance("FirstFragment, Instance 1");
                case 1:
                    return SecondFragment.newInstance();
                case 2:
                    return ThirdFragment.newInstance("ThirdFragment, Instance 1");
                case 3:
                    return ThirdFragment.newInstance("ThirdFragment, Instance 2");
                case 4:
                    return ThirdFragment.newInstance("ThirdFragment, Instance 3");
                default:
                    return ThirdFragment.newInstance("ThirdFragment, Default");
            }
        }

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

表示无法解析mMap符号。 我该如何从活动中调用地图?我在这里错了什么?

我正在使用android-support-v4

2 个答案:

答案 0 :(得分:1)

我们无法像你需要的那样实例化任何片段。无法使用Fragment创建bcoz参数化构造函数。

使用以下代码纠正您的代码:

private class MyPagerAdapter extends FragmentPagerAdapter {
    case 1:
      return new SecondFragment.newInstance(); // replace with this line
    break;
}

答案 1 :(得分:0)

首先,您无法使用:

创建片段
<?php
if(isset($_POST['email'])) {
 
    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "jgomez.jr@att.net";
    $email_subject = "Journal Entries Request/Comment";
 
    function died($error) {
        // your error code can go here
        echo "We are very sorry, but there were error(s) found with the form you submitted. ";
        echo "These errors appear below.<br /><br />";
        echo $error."<br /><br />";
        echo "Please go back and fix these errors.<br /><br />";
        die();
    }
 
 
    // validation expected data exists
    if(!isset($_POST['first_name']) ||
        !isset($_POST['last_name']) ||
  
        !isset($_POST['email']) ||
        !isset($_POST['comments'])) 
    //     {
    //     died('We are sorry, but there appears to be a problem with the form you submitted.');       
    // }
 
     
 
    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required

    $telephone = $_POST['email']; // not required
    $comments = $_POST['comments']; // required
 
    // $error_message = "";
    // $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
 
//   if(!preg_match($email_exp,$email_from)) {
//     $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
//   }
 
    // $string_exp = "/^[A-Za-z .'-]+$/";
 
//   if(!preg_match($string_exp,$first_name)) {
//     $error_message .= 'The First Name you entered does not appear to be valid.<br />';
//   }
 
//   if(!preg_match($string_exp,$last_name)) {
//     $error_message .= 'The Last Name you entered does not appear to be valid.<br />';
//   }
 
//   if(strlen($comments) < 2) {
//     $error_message .= 'The Comments you entered do not appear to be valid.<br />';
//   }
 
//   if(strlen($error_message) > 0) {
//     died($error_message);
//   }
 
    
 
     
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
 
     
 
  
    $email_message .= "Name: ".clean_string($last_name)."\n";
    $email_message .= "Email: ".clean_string($email_account)."\n";

    $email_message .= "Comments: ".clean_string($comments)."\n";
 
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);  
?>
 
<!-- include your own success html here -->
 
Thank you for contacting us. We will be in touch with you very soon.
 
<?php
 
}
?>

因为您的SecondFragment上只有一个默认构造函数:

return SecondFragment(GoogleMap mMap);

或静态方法:

public SecondFragment();

创建片段。

而且你也没有使用new关键字创建Fragment。 Java中的每个对象都需要使用public static SecondFragment newInstance(); 创建。除非您new是一种方法。

因此,您需要创建片段:

SecondFragment(GoogleMap mMap);

要访问private class MyPagerAdapter extends FragmentPagerAdapter { case 1: return new SecondFragment.newInstance(); // or // return new SecondFragment(); 变量,您可以在Fragment中使用getter,如下所示:

private GoogleMap mMap;