В этом руководстве объясняется, как добавить настраиваемую интерактивность на настраиваемые вкладки.
Включить действие «Поделиться» по умолчанию
Если вы не предоставляете настраиваемое действие «Поделиться», рекомендуется включить действие «Поделиться» по умолчанию в браузере в дополнительном меню, чтобы пользователям было проще делиться ссылкой на контент, который они просматривают:
CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder(); intentBuilder.setShareState(CustomTabsIntent.SHARE_STATE_ON);
Добавьте кнопку специального действия
Для важных действий панель инструментов «Настраиваемая вкладка» позволяет интегрировать кнопку настраиваемого действия, которая может иметь текстовую метку или собственный значок. Значок должен иметь высоту 24 dp и ширину 24–48 dp.
Например, вы можете добавить на панель инструментов собственное действие «Поделиться». Для этого создайте BroadcastReceiver
, который вызывается, когда пользователь нажимает действие «Поделиться» на настраиваемой вкладке.
Зарегистрируйте BroadCastReceiver
в файле AndroidManifest.xml
:
<application …> <receiver android:name=".ShareBroadcastReceiver" /> </application>
Затем добавьте новый класс ShareBroadcastReceiver
. В методе onReceive()
извлеките отображаемый в данный момент URL-адрес из намерения и инициируйте намерение отправки.
public class ShareBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String url = intent.getDataString(); Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, url); sendIntent.setType("text/plain"); Intent shareIntent = Intent.createChooser(sendIntent, null); shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(shareIntent); } }
Теперь создайте PendingIntent
для ShareBroadcast
и зарегистрируйте его с помощью setActionButton()
. Передайте ожидающее намерение вместе со значком и описанием.
String shareDescription = getString(R.string.label_action_share); Bitmap shareIcon = BitmapFactory.decodeResource(getResources(), android.R.drawable.ic_menu_share); // Create a PendingIntent to your BroadCastReceiver implementation Intent actionIntent = new Intent( this.getApplicationContext(), ShareBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0 /* request code */, actionIntent, PendingIntent.FLAG_MUTABLE); //Set the pendingIntent as the action to be performed when the button is clicked. CustomTabsIntent intentBuilder = new CustomTabsIntent.Builder() … .setActionButton(shareIcon, shareDescription, pendingIntent) .build();
Добавляйте пользовательские пункты меню
Пользовательская вкладка имеет до пяти действий по умолчанию, предоставляемых браузером: «Вперед», «Информация о странице», «Обновить», «Найти на странице» и «Открыть в браузере». Кроме того, вы можете добавить еще до семи. Эти элементы меню будут вставлены между строкой значков и элементами, предоставленными браузером. (См. изображение ниже.) Фактическое число зависит от базовой реализации браузера. (Например, в версии 117 Chrome увеличил количество пунктов меню с пяти до семи.) Поэтому лучше всего сначала добавлять самые важные пункты.
Вы можете получить доступ к своим пользовательским действиям через трехточечное меню в правом верхнем углу:
Чтобы добавить элемент меню, вызовите CustomTabsIntent.Builder.addMenuItem()
с заголовком и PendingIntent
. Когда пользователь нажимает на пункт меню, браузер запускает PendingIntent
.
CustomTabsIntent intent = new CustomTabsIntent.Builder() ... .addMenuItem("Menu item 1", pendingIntent) .addMenuItem("Menu item 2", pendingIntent) .addMenuItem("Menu item 3", pendingIntent) .addMenuItem("Menu item 4", pendingIntent) .addMenuItem("Menu item 5", pendingIntent) .build();
Настройте кнопку закрытия
Чтобы лучше вписать пользовательскую вкладку в рабочий процесс вашего приложения, настройте кнопку закрытия. Если вы хотите, чтобы пользователь чувствовал, что «Пользовательские вкладки» — это модальное диалоговое окно, используйте кнопку “X”
по умолчанию. Если вы хотите, чтобы пользователь чувствовал, что пользовательская вкладка является частью потока приложения, используйте стрелку назад.
CustomTabsIntent.Builder intentBuilder = new CustomTabsIntent.Builder(); intentBuilder.setCloseButtonIcon(BitmapFactory.decodeResource( getResources(), R.drawable.ic_arrow_back));
Добавить нижнюю панель инструментов
Нижняя панель инструментов — это очень гибкий способ добавить больше функциональности настраиваемой вкладке.
Передав объект RemoteViews
в CustomTabIntent.Builder.setSecondaryToolbarViews() , нижнюю панель инструментов можно полностью настроить и динамически обновлять.
Сначала объявите макет панели инструментов, создав новый файл макета res/layout/custom_tab_toolbar.xml
:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center"> <Button xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/ct_toolbar_next" android:layout_width="wrap_content" android:layout_height="48dp" android:layout_margin="8dp" android:padding="8dp" android:paddingStart="16dp" android:paddingEnd="16dp" android:text="Next" /> <Button xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/ct_toolbar_previous" android:layout_width="wrap_content" android:layout_height="48dp" android:layout_margin="8dp" android:padding="8dp" android:text="Previous" /> </LinearLayout>
Следующим шагом является регистрация BroadcastReceiver
, который обрабатывает взаимодействие с панелью инструментов, в файле AndroidManifest.xml
:
<application …> <receiver android:name=".CustomTabBottomToolbarBroadcastReceiver" /> </application>
Затем реализуйте BroadcastReceiver
, который будет обрабатывать все взаимодействия с нижней панелью инструментов:
public class BottomToolbarBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String url = intent.getDataString(); int remoteViewId = intent.getIntExtra(EXTRA_REMOTEVIEWS_CLICKED_ID, -1); if (remoteViewId == R.id.ct_toolbar_previous) { // handle previous } else if (remoteViewId == R.id.ct_toolbar_next) { // handle next } } }
Наконец, зарегистрируйте панель инструментов:
// Create the pending intent Intent actionIntent = new Intent( this.getApplicationContext(), BottomToolbarBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0 /* request code */, actionIntent, PendingIntent.FLAG_MUTABLE); // Pass the toolbar layout to the RemoteViews instance RemoteViews secondaryToolbarViews = new RemoteViews(getPackageName(), R.layout.custom_tab_toolbar); // All toolbar buttons int[] clickableIds = {R.id.ct_toolbar_next, R.id.ct_toolbar_previous}; // Register the bottom toolbar when creating a new custom tab intent CustomTabsIntent intent = new CustomTabsIntent.Builder() .setSecondaryToolbarViews(secondaryToolbarViews, clickableIds, toolbarPendingIntent) .build();
Закладки и кнопки загрузки
Закладки и кнопки загрузки в трехточечном меню включены по умолчанию. Чтобы отключить их, используйте следующий код в CustomTabsIntent.Builder
:
CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder() .setBookmarksButtonEnabled(false) .setDownloadButtonEnabled(false) .build();
Далее: узнайте, как ускорить загрузку веб-контента на пользовательской вкладке .