Перейти к содержанию

Имплементация Webim Mobile Widget в Android-приложение

Webim Mobile Widget - это полноценный компонент просмотра чата, содержащий в себе всё необходимое. Webim Mobile Widget является обычным компонентом View ОС Android и может быть легко интегрирован в приложение как посредством XML-конфигурации, так и через код приложения. В этом компоненте все значения по умолчанию уже заданы, но могут быть переопределены в соответствии с Вашими потребностями - например, для сходства интерфейса виджета с графической темой интерфейса приложения.

Webim Mobile Widget основан на Mobile SDK, и потому его использование будет отличной альтернативой для тех, у кого недостаточно времени или знаний для использования SDK.

Ниже приведена инструкция по установке и использованию Webim Mobile Widget в ваше мобильное приложение.

Добавление билиотеки в зависимости

// kotlin dsl
dependencies {
    implementation("ru.webim.sdk:chatview:<LAST_VERSION>)
}
// groovy
dependencies {
    implementation("ru.webim.sdk:chatview:<LAST_VERSION>")
}

Настройка Webim Mobile Widget

ChatView - это обычный компонент представления, задаваемый как через код, так и через XML-макеты.

XML

<ru.webim.chatview.ui.ChatView
    android:id="@+id/chatView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:chv_account_name="https://demo.webim.ru"
    app:chv_location_name="mobile" />

Параметры chv_account_name и chv_location_name определяют ваш аккаунт Webim и используемое размещение соответственнно. Эти параметры так же могут быть изменены в коде путём спецификации сессии Webim..

Java

Внутренняя логика мобильного виджета основана на Webim Mobile SDK. Поэтому, чтобы настроить просмотр чата, передайте ему настроенную сессию, которую вы ранее использовали для работы с Webim Mobile SDK. Вам необходимо передать сессию Webim в ChatView с помощью метода ChatView#setSession. Теперь ChatView сделает всю работу за вас.

ChatView chatView = new ChatView(getContext());
chatView.setSession(session);
containerView.addView(chatView);

Сессия устанавливается следующим образом:

WebimSession session = Webim.newSessionBuilder()
    .setContext(getContext())
    .setAccountName("https://demo.webim.ru")
    .setLocation("mobile")
    ...
    .build();

Далее представление отвечает за работу с сессией, запуск, остановку и её уничтожение.

Установка представления чата программно позволяет Вам кастомизировать чат более гибко. Также допустимо использование комбинации настройки параметров в коде и XML-макетов. Объявите представление чата в разметке, найдите его в коде и установите сессию для него.

Кастомизация темы

Вы можете изменять цвета по умолчанию компонента отображения чата. Вы можете сделать это, например, создав свой собственный стиль, унаследованный от ChatViewDefaultStyle.

<style name="MyChatTheme" parent="ChatViewDefaultStyle">
    <item name="chv_bar_background">@color/white</item>
    <item name="chv_message_border">@color/message_border</item>
    ...
</style>

Затем, в макете укажите созданный Вами стиль в поле app:chv_chat_style объекта ChatView. Пример приведён ниже:

<ru.webim.chatview.ui.ChatView
    android:id="@+id/chatView"
    app:chv_chat_style="@style/MyChatTheme"
    ...
    />

Существует достаточно большое количество параметров, доступных для изменения. Они приведены ниже в таблице с указанием названия и используемого типа данных.

Style item Type
chv_primary_color integer or color
chv_secondary_color integer or color
chv_accent_color integer or color
chv_bar_background integer or color
chv_message_border integer or color
chv_text_light integer or color
chv_text_strong integer or color
chv_text_medium integer or color
chv_text_hint integer or color
chv_sent_bubble integer or color
chv_sent_text integer or color
chv_sent_link_text integer or color
chv_sent_time_text integer or color
chv_sent_edited_text integer or color
chv_sent_selected integer or color
chv_sent_divider integer or color
chv_sent_file_data integer or color
chv_received_bubble integer or color
chv_received_text integer or color
chv_received_link_text integer or color
chv_received_time_text integer or color
chv_received_edited_text integer or color
chv_received_selected integer or color
chv_received_divider integer or color
chv_received_sender_name integer or color
chv_system_bubble integer or color
chv_system_text integer or color
chv_system_link_text integer or color
chv_system_time_text integer or color
chv_buttons_background integer or color
chv_buttons_pending integer or color
chv_buttons_complete integer or color
chv_buttons_canceled integer or color
chv_message_replied integer or color
chv_prompt_syncing integer or color
chv_prompt_net_lost integer or color
chv_prompt_net_losing integer or color
chv_message_text_size dimension
chv_message_corner_radius dimension
chv_message_menu_background integer or color
chv_chat_menu_background integer or color