我有 2 个 Activity ,第一个是空白 Activity ,第二个是 map Activity 。我正在尝试在顶部导航栏上为第二个 Activity ( map Activity )设置一个后退按钮,以便能够转到主要 Activity 。
当我运行以下代码时出现异常。看到提出了类似的问题,但它们是空白 Activity 而不是 map Activity 。此外,建议是更改我要扩展的类(class)。考虑到这会扰乱 map Activity 的默认代码实现,我不知道这将如何工作。请指教。
报错信息和我的代码如下。我正在使用 Holo Light 作为主题。
Exception:
Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
map Activity 代码
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);
//ERROR message occurring on these line
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
list - 为 MapActivity 应用父级名称
<activity
android:name=".MapsActivity"
android:parentActivityName=".MainActivity"
android:label="@string/title_activity_maps"></activity>
最佳答案
来自 FragmentActivity 文档
http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html
Note: If you want to implement an activity that includes an action bar, you should instead use the ActionBarActivity class, which is a subclass of this one, so allows you to use Fragment APIs on API level 7 and higher.
此外,由于您正在使用支持库,所以应该是
ActionBar actionBar = getSupportActionBar();
关于java - 调用Action Bar导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34097494/