Android:getActionBar()返回null值

时间:2015-02-18 23:35:27

标签: android android-activity android-fragments android-actionbar

我正在尝试禁用ActionBar上的后退按钮。但是,当我在onCreate()中执行getActionBar()时,我得到一个空值。有什么想法吗?

的AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:noHistory="true"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
          <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

MainActivity.java

public class MainActivity extends ActionBarActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getApplicationContext();
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        android.app.ActionBar a = getActionBar();
        a.setDisplayHomeAsUpEnabled(false);
    }

    public static class PlaceholderFragment extends Fragment {
        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main,container, false);
            return rootView;
        }
    }
}

1 个答案:

答案 0 :(得分:4)

尝试使用这行代码

getSupportActionBar().setDisplayHomeAsUpEnabled(false);

而不是

android.app.ActionBar a = getActionBar();
a.setDisplayHomeAsUpEnabled(false);