在Android 2.3中无法使用Action bar和Fragment

时间:2014-01-15 19:01:45

标签: android android-fragments android-actionbar

我想在Android 2.3中使用Action bar和Fragment,但是有一个错误

Type mismatch: cannot convert from android.app.ActionBar to android.support.v7.app.ActionBar

在这一行

final ActionBar bar = getActionBar();

我已经导入了android.support.v4和v7。

package com.hmkcode.android;

import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends FragmentActivity {
private ViewPager pager;
private TabsAdapter mTabsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pager = new ViewPager(this);
    pager.setId(R.id.pager);
    setContentView(pager);

    final ActionBar bar = getActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mTabsAdapter = new TabsAdapter(this, pager);
    mTabsAdapter.addTab(bar.newTab().setText("List Fragment 1"), List_View.class, null);
    mTabsAdapter.addTab(bar.newTab().setText("List Fragment 2"), List_View.class, null);
    mTabsAdapter.addTab(bar.newTab().setText("List Fragment 3"), List_View.class, null);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    //return true;
    MenuItem item1 = menu.add(0, 1, 1, "Change role");
    item1.setShortcut('1', '1');

    MenuItem item2 = menu.add(0, 2, 2, "User Information");
    item2.setShortcut('2', '2');

    return super.onCreateOptionsMenu(menu);
}

}

1 个答案:

答案 0 :(得分:17)

确保您引用了AppCompat

http://developer.android.com/tools/support-library/setup.html

变化

public class MainActivity extends FragmentActivity {
    ...
}

public class MainActivity extends ActionBarActivity { 
    ...
}

并更改

final ActionBar bar = getActionBar();

final ActionBar bar = getSupportActionBar();  

参考

http://developer.android.com/guide/topics/ui/actionbar.html

你为什么还需要

setContentView(R.layout.activity_main);

当你有

setContentView(pager);