无法从导航抽屉中调用活动

时间:2019-02-14 12:48:15

标签: android

我们有一个导航抽屉,我们要从中调用一个包含Google地图的活动。 这是MapsActivity.java

的代码
package com.sahayatra.samyatra;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
{

    private GoogleMap mMap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        Button btn=(Button)findViewById(R.id.offer_a_ride);
        btn.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MapsActivity.this,ToFromO9Activity.class));
            }
        });
        Button btn1=(Button)findViewById(R.id.find_a_ride);
        btn1.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MapsActivity.this,ToFromF10Activity.class));
            }
        });
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(MapsActivity.this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @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));
    }
}

Main8Navigation.java的代码:-

package com.sahayatra.samyatra;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

public class Main8navigation extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
    DrawerLayout drawer;
    Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main8navigation);
        toolbar=findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        drawer=findViewById(R.id.drawer_layout);
        NavigationView navigationView=findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this );
        ActionBarDrawerToggle toggle=new ActionBarDrawerToggle(this,drawer,toolbar,R.string.navigation_drawer_open,R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new HomeFragment()).commit();
        navigationView.setCheckedItem(R.id.nav_home);

    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.nav_myaccount:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new MyAccountFragment()).commit();

                break;
            case R.id.nav_fav:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new FavouritesFragment()).commit();

                break;
            case R.id.nav_block:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new BlockFragment()).commit();

                break;
            case R.id.nav_home:
               getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,new HomeFragment()).commit();


                break;
        }
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

这是HomeFragment.java,我们要在其中调用MapsActivity.java:-

package com.sahayatra.samyatra;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class HomeFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        ((MapsActivity)getActivity()).onCreate(savedInstanceState);
        return inflater.inflate(R.layout.fragment_home,container,false);

    }
}

这是导航抽屉的xml文件:-

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer_layout"
    android:fitsSystemWindows="true"
    tools:context=".Main8navigation"
    tools:openDrawer="start"
    >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/white"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"
        />

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>
</LinearLayout>
    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/drawer_menu">

    </android.support.design.widget.NavigationView>


</android.support.v4.widget.DrawerLayout>

这是MapsActivity的xml文件:-

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical">


    <FrameLayout
        android:layout_width="350dp"
        android:layout_height="300dp"
        android:layout_marginStart="18dp"
        android:layout_marginEnd="18dp"
        android:layout_marginTop="100dp">

        <fragment
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context="com.sample.sishin.maplocation.MapsActivity" />
        <LinearLayout
            android:id="@+id/locationMarker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginBottom="30dp"
            android:gravity="center"
            android:orientation="vertical" >
            <ImageView
                android:id="@+id/imageMarker"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />
        </LinearLayout>



    </FrameLayout>
    <Button
        android:id="@+id/offer_a_ride"
        android:layout_width="150dp"
        android:layout_height="80dp"
        android:layout_marginBottom="1dp"
        android:layout_marginTop="480dp"
        android:layout_marginEnd="200dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="20dp"
        android:text="OFFER A RIDE"
        android:textColor="@color/white"
        android:background="@drawable/mybutton"
        />
    <Button
        android:id="@+id/find_a_ride"
        android:layout_width="200dp"
        android:layout_height="80dp"
        android:layout_marginBottom="1dp"
        android:layout_marginTop="480dp"
        android:layout_marginEnd="20dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="220dp"
        android:text="FIND A RIDE"
        android:textColor="@color/white"
        android:background="@drawable/mybutton"
      />
</RelativeLayout>

这是AndroidManifest:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sahayatra.samyatra">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <uses-feature android:name="android.hardware.location.gps" />

    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoTitleBar">
        <activity
            android:name=".MainActivity"
            android:label="Samyatra">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Main3Activity" />
        <activity android:name=".LogoActivity" />
        <activity android:name=".Main2Activity" />
        <activity android:name=".Main1Activity" />
        <activity android:name=".Main4Activity" />
        <activity android:name=".Main5Activity" />
        <activity android:name=".Main6Activity" />
        <activity android:name=".Main7Activity" />
        <activity
            android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
            android:screenOrientation="portrait" />
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyD1bUfbDXswczR-DtXfgig2acAdERY6WQg" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps"
       />
        <activity android:name=".Main8navigation" />

        <service
            android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
            android:enabled="true" />

        <activity android:name=".MyAcc9Activity" />
        <activity android:name=".ToFromO9Activity" />
        <activity android:name=".ToFromF10Activity"></activity>
    </application>

</manifest>

1 个答案:

答案 0 :(得分:0)

您应该使用startActivity来启动Activity,而不是通过手动调用该Activity的onCreate方法来实现。

因此,在您这种情况下,请在HomeFragment.java内添加以下代码行:

startActivity(new Intent(getActivity(), MapsActivity.class));

并删除该行:

((MapsActivity)getActivity()).onCreate(savedInstanceState)