androidandroid-studioandroid-actionbarandroid-actionbaractivity

Cannot create tabs in action bar using ActionBarActivity


I am absolute beginner to Android. I am about to create action bar with tabs. But my Android SDK version is too low. So I tried to use old way of creating action bar with tabs using ActionBarActivity. I want to know both old and new ways as well. Now I doing like this.

My activity class

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar bar = getSupportActionBar();

        bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        for(int i = 1;i<=3;i++){
            ActionBar.Tab tab = bar.newTab();
            tab.setText("Tab" + i);
            bar.addTab(tab);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

</resources>

But when I run my app. It is throwing error. What is wrong with my code?


Solution

  • Do not use ActionBarActivity since it is deprecated.

    And you are using:

    Theme.AppCompat.Light.DarkActionBar
    

    with : ActionBarActivity

    Change it to AppCompatActivity in your java codes(Activity).

    This should solve the problem. and of course if you are using AppCompat:

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbarmain);
            setSupportActionBar(toolbar);
    

    similiar questions:

    Android getActionBar vs getSupportActionBar?