2014-01-15 65 views
4

操作欄和片段我想使用Android 2.3的動作條和片段,但有一個錯誤不能使用的Android 2.3

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

} 
+0

已引用appcompat – Raghunandan

回答

17

確保已引用程序兼容性

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);