Search code examples
androidintellij-ideamaterial-designandroid-appcompatandroid-actionbar-compat

getActionBar doesn't work using AppCompat lib


I'm trying to create a TabLayout android app using Intellij Idea and AppCompat v7 library.

import android.support.v7.app.ActionBar;

public class MainActivity extends FragmentActivity implements TabListener { 
...
private ActionBar actionBar;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
actionBar = getActionBar(); //Error line
...

}

When using getActionBar() I'm getting this error:

Incompatibale types:

Required: android.support.v7.app.ActionBar

Found: android.app.ActionBar

I don't have import android.app.ActionBar; in my activity. I tried:

actionBar = android.support.v7.app.ActionBar.getActionBar();

and

actionBar = getSupportActionBar();

But I get

Can't resolve method getActionBar() //Or getSupportActionBar()

How can I use getActionBar() using appCompat library? (Or maybe there is an alternative which I don't know about?)

Edit

I also replaced FragmentActivity with ActionBarActivity in this line:

 public class MainActivity extends FragmentActivity //ActionBarActivity

But got no luck


Solution

  • Bad Approach

    Calling older import android.support.v7.app.ActionBar;

    If you are extending AppCompatActivity/FragmentActivity then you are providing backward support for older Android Versions and for that you should have to use getSupportActionBar().

    Read getSupportActionBar using FragmentActivity

    public class MainActivity extends AppCompatActivity {
      // ...
    
      ....
    
     ActionBar actionBar =getSupportActionBar();
    }
    

    Add this .

    dependencies {
       // … 
       compile 'com.android.support:appcompat-v7:23.1.0'
    }
    

    Check Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?

    AppCompatActivity is from the appcompat-v7 library. Principally, this offers a backport of the action bar. Since the native action bar was added in API Level 11, you do not need AppCompatActivity for that.

    For your Information How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA