将一个 Activity 转换为另一个 activity 的片段 (android)

Convert an Activity into Fragment for another activity (android)

所以我很难理解这些东西是如何工作的。 我有一个名为 MapsActivity 的 activity。它的签名是:

package com.ap2.demoapp;

import android.app.ActivityManager;

import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    private boolean enter = false;
    // define :
    private static final int SECONDS = 1000;
    private static final long INTERVAL = 10 * SECONDS;
    private static final long FASTEST_INTERVAL = 5 * SECONDS;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();

        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        createLocationRequest();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

    }
    @Override
    public void onStart() {
        super.onStart();
        mGoogleApiClient.connect();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!enter && mGoogleApiClient.isConnected()) {
            enter = true;
            startLocationUpdates();
        }
        setUpMapIfNeeded();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (enter && mGoogleApiClient.isConnected()) {
            stopLocationUpdates();
            enter = false;
        }

    }
    @Override
    public void onStop() {
        super.onStop();
        mGoogleApiClient.disconnect();
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
                //animation

                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(5000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
                t.start();
            }
        }
    }


    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("My Location"));
    }

    @Override
    public void onConnected(Bundle bundle) {
        Toast.makeText(this,"Starting location updates",Toast.LENGTH_SHORT).show();
        startLocationUpdates();
    }
    protected void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
                mLocationRequest, (com.google.android.gms.location.LocationListener) this);
    }
    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
                (com.google.android.gms.location.LocationListener) this);
    }
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this,"Failed to connect location updates",Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onLocationChanged(final Location location) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(new LatLng(location.getLatitude(),location.getLongitude())) // Sets the center of the map
                        .zoom(17) // Sets the zoom
                        .bearing(90) // Sets the orientation of the camera to east
                        .tilt(30) // Sets the tilt of the camera to 30 degrees
                        .build(); // Creates a CameraPosition from the builder

                mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }
        });
    }


    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (status == ConnectionResult.SUCCESS) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this,0).show();
            return false;
        }
    }
    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }


}

XML:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:id="@+id/map"
    tools:context="com.ap2.demoapp.MapsActivity"
    android:name="com.google.android.gms.maps.SupportMapFragment" />

现在我有一个主要的 activity 看起来像这样:

package com.ap2.demoapp;

import android.content.res.Configuration;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

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

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                Fragment newFragment   = new MainFragment();
                FragmentManager fm     = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();

                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    ft.add(R.id.menuFragment, new MenuFragment());
                }
                // adding the fragment:


                ft.add(R.id.mainFragment, getSupportFragmentManager().findFragmentById(R.id.map)); // always NULL


                ft.commit();
            }
        });
        t.start();
    }


}

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#001122"
    tools:context="com.ap2.demoapp.MainActivity">

    <RelativeLayout
        android:id="@+id/mainFragment"
        android:background="#ffffff"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="2"
        ></RelativeLayout>



</RelativeLayout>

有人知道我做错了什么吗? 我想将我的 MapsActivity 作为 MainActivity 中的片段激活。

有人知道我该怎么做吗?

提前致谢。

您不能使用将任何 "Activity" 扩展为片段的 class。它需要扩展片段。在这种情况下,我只会将地图片段放在 activity 布局中。

第一个解决方案

在 Activity 布局中添加地图片段

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#001122"
    tools:context="com.ap2.demoapp.MainActivity">

    <fragment 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>

Activity

public class MainActivity extends ActionBarActivity {
    GoogleMap mMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mMap == null) {
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        }
    }
}

在 MainActivity class.

中调用所有工具
public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener

运行这个,告诉我它是否显示地图。

第二种解法

主要Activity

public class MainActivity extends ActionBarActivity {
    GoogleMap mMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         getSupportFragmentManager().beginTransaction().replace(R.id.mainFragment, new MapsActivity()).commit();
    }
}

activity_main.xml

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#001122"
    tools:context="com.ap2.demoapp.MainActivity">

    <RelativeLayout
        android:id="@+id/mainFragment"
        android:background="#ffffff"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="2" />

</RelativeLayout>

片段

public class MapsActivity extends Fragment {
    View v;
    GoogleMap mMap;
    public MapsActivity() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.activity_mapsactivity, container, false);
        if (mMap == null) {
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
        }
        return v;
    }

片段布局

<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:id="@+id/map"
    tools:context="com.ap2.demoapp.MapsActivity"
    android:name="com.google.android.gms.maps.SupportMapFragment" />