Библиотека appcompat - lanit-tercom-school/grouplock GitHub Wiki

Библиотека AppCompat (aka ActionBarCompat) появилась как порт нового ActionBar API из Android 4.0 на устройства с Gingerbread. Она представила общий слой API поверх бэкпортированной либо стандартной реализации. AppCompat v21 же приносит API и набор возможностей из Android 5.0

В этой версии Android появился новый виджет Toolbar. Он представляет собой обобщение шаблона ActionBar и дает больше контроля и гибкости. Toolbar — это элемент view в общей иерархии, что упрощает реализацию его взаимодействия с другими виджетами, анимации и реакции на события прокрутки. Так же вы можете использовать его как Actionbar вашей активности, а это значит, что стандартные элементы меню действий будут показываться в нем.

Вы, вероятно, уже пользовались какое-то время обновленной версией AppCompat. Эта библиотека была включена в обновления различных программ Google, вышедшие в последние недели, в том числе Play Маркет и Play Пресса.

###Темы оформления

AppCompat поддерживает новые атрибуты цветовой палитры, которые позволяют настроить тему под ваш брэнд, используя основной и акцентный цвета. Например: values/themes.xml:

<style name="Theme.MyTheme" parent="Theme.AppCompat.Light"> @color/my_awesome_color @color/my_awesome_darker_color @color/accent </style>

Когда вы зададите эти атрибуты, AppCompat автоматически применит их как значения атрибутов из API 21+. А это, в свою очередь, окрасит панель статуса и элемент в списке недавних задач. 

На более старых платформах, AppCompat эмулирует цветовые темы, когда это возможно. В текущий момент, это ограничивается окрашиванием панели действий и некоторыми виджетами. ###Тонировка виджетов

Когда вы запускаете приложение на устройстве с Android 5.0, все виджеты тонируются цветом, указанным в атрибутах темы. Есть две основные возможности, которые позволяют это делать на Lollipop: тонировка drawable и ссылки на аттрибуты тем (в формате ?attr/foo) внутри drawable.

AppCompat предлагает похожее поведение на ранних версиях Android для следующего множества UI виджетов: Все, что предлагается в AppCompat toolbar (режимы действий и прочее) EditText Spinner CheckBox RadioButton Switch (используйте новый класс android.support.v7.widget.SwitchCompat) CheckedTextView

Вам ничего не нужно делать специально, чтобы это заработало. Используйте эти элементы в вашей разметке как обычно, а AppCompat сделает остальное (с некоторыми оговорками, см. FAQ ниже).  ###Виджет панели инструментов (Toolbar)

Toolbar полностью поддерживается библиотекой AppCompat и полностью полностью соответствует как по возможностям, так и по API вызовам, виджету из SDK. В AppCompat, панель инструментов реализуется с помощью класса android.support.v7.widget.Toolbar. Есть два способа её применения: Использовать как ActionBar, если вы хотите использовать существующие возможности Action Bar (такие, как внедрение меню, выделение, ActionBarDrawerToggle и т.д.), но при этом хотите больше контроля над её внешним видом. Использовать автономную панель в ситуациях, когда обычный ActionBar не подходит. Например, чтобы показать несколько панелей на экране, занять только часть экрана по ширине и т.д.

###Action Bar

Чтобы использовать Toolbar в качестве ActionBar, во-первых, отключите обычный ActionBar. Самый простой способ сделать это — унаследовать вашу тему отTheme.AppCompat.NoActionBar (или светлого её варианта)

Во-вторых, создайте экземпляр панели инструментов. Например, включив её в ваш xml-файл разметки <android.support.v7.widget.Toolbar android:id="@+id/my_awesome_toolbar" android:layout_height="wrap_content" android:layout_width="match_parent" android:minHeight="?attr/actionBarSize" android:background="?attr/colorPrimary" />

Высота, ширина, фон и прочее теперь полностью зависят от вас, это просто хороший пример. Так как Toolbar — это просто ViewGourp, вы можете стилизовать и позиционировать его на своё усмотрение.

И наконец, установите Toolbar в качестве ActionBar в вашей активности или фрагменте:

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.blah);

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);
    }

Начиная с этого момента все элементы меню будут отображаться в вашей панели инструментов, наполняясь с помощью стандартных вызовов настройки меню. Автономное использование

Отличие автономного режима в том, что вы не задаете Toolbar в качестве ActionBar. Поэтому, вы можете использовать любую тему AppCompat и вам не нужно отключать обычный ActionBar.

В автономном режиме вы можете наполнять Toolbar содержимым или действиями. Например, если вы хотите показать действия, вам нужно внедрить меню:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.blah);

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);

    // Set an OnMenuItemClickListener to handle menu item clicks
    toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            // Handle the menu item
            return true;
        }
    });

    // Inflate a menu to be displayed in the toolbar
    toolbar.inflateMenu(R.menu.your_toolbar_menu);
}

Есть множество других вещей, которые можно делать с панелью инструментов. Для получения дополнительной информации, смотрите описание Toolbar API.

###Стили

Настройка стиля панели инструментов отличается от того, как это делалось для стандартной панели действий. Стиль применяется прямо к самому виджету. 

Вот основной стиль, который вы должны использовать, когда вы используете Toolbar в качестве ActionBar:

<android.support.v7.widget.Toolbar  
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

Объявление app:theme позволит убедиться, что шрифт и элементы используют чистый цвет (например, 100% непрозрачный белый).

###Темная панель действий Вы можете настроить панель инструментов напрямую, используя атрибуты разметки. Чтобы Toolbar выглядела как «DarkActionBar» (тёмное содержимое, светлое меню переполнения), укажите атрибуты theme и popupTheme:

<android.support.v7.widget.Toolbar
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="@dimen/triple_height_toolbar"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

###Виджет поиска (SearchView)

AppCompat предлагает обновленное API для виджета поиска, которое поддается большей настройке и стилизации. Теперь мы используем структуру стилей из Lollipop вместо старых searchView* аттрибутов темы.

Вот как вы можете настроить стиль SearchView: values/themes.xml:

<style name="Theme.MyTheme" parent="Theme.AppCompat">
    <item name="searchViewStyle">@style/MySearchViewStyle</item>
</style>
<style name="MySearchViewStyle" parent="Widget.AppCompat.SearchView">
    <!-- Background for the search query section (e.g. EditText) -->
    <item name="queryBackground">...</item>
    <!-- Background for the actions section (e.g. voice, submit) -->
    <item name="submitBackground">...</item>
    <!-- Close button icon -->
    <item name="closeIcon">...</item>
    <!-- Search button icon -->
    <item name="searchIcon">...</item>
    <!-- Go/commit button icon -->
    <item name="goIcon">...</item>
    <!-- Voice search button icon -->
    <item name="voiceIcon">...</item>
    <!-- Commit icon shown in the query suggestion row -->
    <item name="commitIcon">...</item>
    <!-- Layout for query suggestion rows -->
    <item name="suggestionRowLayout">...</item>
</style>

Вам не нужно указывать все (или вообще какие-то) из аттрибутов. Значения по-умолчанию должны подойти большинству приложений.

##ActionBarCompat and I/O 2013 App Source Posted by Chris Banes, Android Developer Relations Following on the Android 4.3 and Nexus 7 announcements, we recently released two important tools to help you build beautiful apps that follow Android Design best practices: We released a new backward-compatible Action Bar implementation called ActionBarCompat that's part of the Support Library r18. The ActionBarCompat APIs let you build the essential Action Bar design pattern into your app, with broad compatibility back to Android 2.1. We released the full source code for the I/O 2013 app, which gives you working examples of ActionBarCompat, responsive design for phones and tablets, Google+ sign-in, synchronized data kept fresh through Google Cloud Messaging, livestreaming using the YouTube Android Player API, Google Maps API v2, and much more. All of the app code and resources are available for you to browse or download, and it's all licensed under Apache License 2.0/Creative Commons 3.0 BY so you can reuse it in your apps. You can get the source at code.google.com/p/iosched This post helps you get started with ActionBarCompat, from setting up the Support Library to adding an Action Bar to your UI. If you want to see ActionBarCompat in action first, download the I/O 2013 app from Google Play and give it a try. The app's Action Bar is built using the ActionBarCompat and served as our main test environment for making sure the APIs work properly, with full compatibility across platform versions.   ###Getting Started with ActionBarCompat ActionBarCompat is a new API in the Android Support Library that allows you to add an Action Bar to applications targetingminSdkVersion 7 or greater. The API and integration have been designed to closely mirror the existing framework APIs, giving you an easy migration path for your existing apps. If you've already using another implementation of Action Bar in your app, you can choose whether to ActionBarCompat. If you’re using the old ActionBarCompat sample available through the SDK, then we highly recommend that you upgrade to the new ActionBarCompat API in the Support Library. If you’re using a third-party solution (such as ActionBarSherlock), there are a few reasons to consider upgrading: Can be kept updated as the Action Bar API evolves. Integrated Ancestral Navigation support. Use of framework Menu and MenuItem classes. Continue to use the Support Library's Fragment class. Integrated support for ActionBarDrawerToggle for use with DrawerLayout. Backport of PopupMenu. ActionBarSherlock is a solid and well-tested library which has served developers very well for a long time. If you are already using it and do not currently require any of the above then there is no need to migrate. If you are ready to get started with ActionBarCompat, the sections below take you through the process.

Add ActionBarCompat as a project dependency

ActionBarCompat is distributed as both a Gradle artifact and a library project. See Setting Up the Support Library for more information.

Update your style resources

The first thing to update are your Activity themes so they use a Theme.AppCompat theme. If you're currently using one of theTheme.Holo themes then just replace this with the related Theme.AppCompat theme. For instance if you have the following in yourAndroidManifest.xml:

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

You would change it to:

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

Things get more tricky when you have a customized theme. The first thing to do is change your base theme to one of theTheme.AppCompat themes, like above. If you have customized styles for the Action Bar (and related widgets) then you must also change these styles to extend from theWidget.AppCompat version. You also need to double-set each attribute: once in the Android namespace and again with no namespace (the default namespace). For example, in the following example we have a custom theme which extends from Theme.Holo.Light, which references a custom Action Bar style.

<style name="Theme.Styled" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item>
</style>

<style name="Widget.Styled.ActionBar" 
    parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:background">@drawable/ab_custom_solid_styled</item>
    <item name="android:backgroundStacked"
        >@drawable/ab_custom_stacked_solid_styled</item>
    <item name="android:backgroundSplit"
        >@drawable/ab_custom_bottom_solid_styled</item>
</style>

To make this work with AppCompat you would move the above styles into the values-v14 folder, modifying each style's parent to be an AppCompat version.

<style name="Theme.Styled" parent="@style/Theme.AppCompat.Light">
    <!-- Setting values in the android namespace affects API levels 14+ -->
    <item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item>
</style>

<style name="Widget.Styled.ActionBar" parent="@style/Widget.AppCompat.Light.ActionBar">
    <!-- Setting values in the android namespace affects API levels 14+ -->
    <item name="android:background">@drawable/ab_custom_solid_styled</item>
    <item name="android:backgroundStacked"
      >@drawable/ab_custom_stacked_solid_styled</item>
    <item name="android:backgroundSplit"
      >@drawable/ab_custom_bottom_solid_styled</item>
</style>

You would then need add the following into the values folder:

<style name="Theme.Styled" parent="@style/Theme.AppCompat.Light">
    <!-- Setting values in the default namespace affects API levels 7-13 -->
    <item name="actionBarStyle">@style/Widget.Styled.ActionBar</item>
</style>

<style name="Widget.Styled.ActionBar" parent="@style/Widget.AppCompat.Light.ActionBar">
    <!-- Setting values in the default namespace affects API levels 7-13 -->
    <item name="background">@drawable/ab_custom_solid_styled</item>
    <item name="backgroundStacked">@drawable/ab_custom_stacked_solid_styled</item>
    <item name="backgroundSplit">@drawable/ab_custom_bottom_solid_styled</item>
</style>

Modify Menu resources

As with the standard Action Bar in Android 3.0 and later versions, action items are added via the options menu. The difference with ActionBarCompat is that you need to modify your Menu resource files so that any action item attributes come from ActionBarCompat's XML namespace. In the example below you can see that a new "yourapp" namespace has been added to the menu element, with the showAsAction andactionProviderClass attributes being provided from this namespace. You should also do this for the other action item attributes (actionLayout and actionViewClass) if you use them.

<menu xmlns:yourapp="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/menu_share"
        android:title="@string/menu_share"
        yourapp:actionProviderClass="android.support.v7.widget.ShareActionProvider"
        yourapp:showAsAction="always" />
    ...
</menu>

Extend Activity classes from ActionBarCompat

ActionBarCompat contains one Activity class which all of your Activity classes should extend: ActionBarActivity. This class itself extends from FragmentActivity so you can continue to use Fragments in your application. There is not a ActionBarCompat Fragment class that you need to extend, so you should continue using android.support.v4.Fragment as the base class for your Fragments.

Add Menu callbacks

To display items on the Action Bar, you need to populate it by overriding onCreateOptionsMenu() and populating the Menu object. The best way to do this is by inflating a menu resource. If you need to call any MenuItem methods introduced in API level 11 or later, you need to call the shim for that method in MenuItemCompat instead. Here's an example:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu
    getMenuInflater().inflate(R.menu.main_menu, menu);

    // Find the share item
    MenuItem shareItem = menu.findItem(R.id.menu_share);

    // Need to use MenuItemCompat to retrieve the Action Provider
    mActionProvider = (ShareActionProvider)
        MenuItemCompat.getActionProvider(shareItem);

    return super.onCreateOptionsMenu(menu);
}

Retrieve the Action Bar

ActionBarCompat contains it’s own ActionBar class, and to retrieve the Action Bar attached to your activity you callgetSupportActionBar(). The API exposed by the compatibility class mirrors that of the framework ActionBar class, allowing you to alter the navigation, show/hide it, and change how it display it’s contents.

Add ActionMode callbacks

To start an action mode from your ActionBarActivity simply call startSupportActionMode(), providing a callback similar to how you would with the native action mode. The following example shows how to start an action mode, inflate a menu resource and react to user’s selection:

startSupportActionMode(new ActionMode.Callback() {
    @Override
    public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
        // Inflate our menu from a resource file
        actionMode.getMenuInflater().inflate(R.menu.action_mode_main, menu);

        // Return true so that the action mode is shown
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
        // As we do not need to modify the menu before displayed, we return false.
        return false;
    }

    @Override
    public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
        // Similar to menu handling in Activity.onOptionsItemSelected()
        switch (menuItem.getItemId()) {
            case R.id.menu_remove:
                // Some remove functionality
                return true;
        }

        return false;
    }

    @Override
    public void onDestroyActionMode(ActionMode actionMode) {
        // Allows you to be notified when the action mode is dismissed
    }
});

Similar to the Activity class, ActionBarActivity provides two methods that you can override to be notified when an action mode is started/finished from within your Activity (including attached Fragments). The methods are onSupportActionModeStarted() and onSupportActionModeFinished().

Add support for Up navigation

Simple example

Up navigation support is built into ActionBarCompat and is similar to that provided in the Android framework in Android 4.1 and higher. In the simplest form, you just need add a reference in each AndroidManifest  element to its logical parent activity. This is done by adding a metadata element to the  element. You should also set the android:parentActivityName attribute for explicit Android 4.1 support, although this is not strictly necessary for ActionBarCompat:

<activity android:name=".SampleActivity"
    android:parentActivityName=".SampleParentActivity">
    <meta-data android:name="android.support.PARENT_ACTIVITY"
        android:value=".SampleParentActivity" />
</activity>

In your Activity you should then configure the home button to display for up navigation:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

When the user now clicks on the home item, the user will navigate up to the parent Activity set in your AndroidManifest.

⚠️ **GitHub.com Fallback** ⚠️