ActionBarCompat - how to use it

允我心安 提交于 2019-11-30 02:15:10

As for implementation, just stick to the sample code provided under the MainActivity.java class. You can find it here or under <your local android-sdks folder>/samples/android-15/ActionBarCompat/src/com/example/android/actionbarcompat/MainActivity.java. In general, all you need to do is the following:

  1. Code a menu resource where you declare the items for the action bar (See http://developer.android.com/resources/samples/ActionBarCompat/res/menu/main.html)
  2. Code an Activity that extends ActionBarActivity
  3. Override onCreateOptionsMenu() so that it inflates the menu you coded in step #1
  4. Override onOptionsItemSelected() so that you handle the event when the user taps any of the ActionBar items you defined in step #1.

I think it makes sense to build an Android Library project out of the ActionBarCompat code; then you can just reference it from your custom Android project. Remember it's licensed under the Apache License, Version 2.0.

This answer describes how to use the new ActionBarCompat library (July 2013).

In Android Studio, open build.gradle and add this:

dependencies {
    compile 'com.android.support:appcompat-v7:18.0.+'
}

In Eclipse, create a library project based on the code in sdk\extras\android\support\v7\appcompat and add it to your project.

Activities have to extend ActionBarActivity.

import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

    ActionBar ab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ab = getSupportActionBar();
        ab.setTitle("Test");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);

        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = 
                    (SearchView) MenuItemCompat.getActionView(searchItem);

        return super.onCreateOptionsMenu(menu);
    }
}

Themes have to be (or extend) one of the Theme.AppCompat themes, for example:

<activity android:theme="@style/Theme.AppCompat.Light" ... />

Source: How to add ActionBarCompat to your project, blog post by Gabriele Mariotti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!