向操作栏添加后退按钮

时间:2016-11-05 14:28:53

标签: android android-studio android-fragments

正如标题所说我想在我的'MapsActivity.java'中的操作栏中添加一个后退按钮,每当单击后退按钮时,我希望用户转到父活动。我尝试使用此处提到的代码:add back button to action bar

现在每当我到达此页面时,都会收到一条消息“很遗憾应用已停止”。 注意:当我使用以下代码时,应用程序才会崩溃:

ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

MapsActivity.java: -

    package com.example.haseeb.memorableplaces;

import android.app.ActionBar;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

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
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        ActionBar actionBar = getActionBar();

        actionBar.setDisplayHomeAsUpEnabled(true);

        Intent i = getIntent();
        Log.i("locationInfo", Integer.toString(i.getIntExtra("locationInfo", -1)));
    }


    /**
     * 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));
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem)
    {
        switch (menuItem.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(menuItem);
        }
    }

}

AndroidManifest.xml: -

<?xml version="1.0" encoding="utf-8"?>

<!--
     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" />

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!--
         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="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:parentActivityName=".MainActivity"
        android:label="@string/title_activity_maps"></activity>
</application>

3 个答案:

答案 0 :(得分:5)

后退按钮应该已经存在而不添加它。如果不存在,则表示您未在Android Manifest中提及父活动。

选项1:

非编程式地,您可以将meta添加到清单文件中的活动

<meta-data
    android:name="android.support.PARENT_ACTIVITY"
    android:value="MainActivity" />

选项2:

onCreate()方法中,插入

getSupportActionBar().setDisplayHomeAsUpEnabled(true); 

覆盖onSupportNavigateUp()方法:

@Override
public boolean onSupportNavigateUp(){ 
    //code it to launch an intent to the activity you want
    finish();  
    return true;  
} 

答案 1 :(得分:0)

您的错误在这里

ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

您正在使用android.support.v4.app.FragmentActivity,但您的ActionBar不是SupportActionBar。在这种情况下,您需要使用此解决方法

ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true);

答案 2 :(得分:0)

选择 Toolbar

ToolBar是在应用程序布局中使用的操作栏的概括。应用程序可以选择使用setActionBar()方法将工具栏指定为Activity的操作栏。

所以我很高兴你添加ToolBar in your layout

code 可以帮助您

相关问题