Android Chat Messaging Tutorial

How to Build Android In-App Messaging with Kotlin or Java.

Learn how to use our Android Chat SDK to create a polished messaging experience with typing indicators, read state, attachments, reactions, user presence, and threads.

Let's start working on everything you need for building in-app messaging into your Android chat application.

Creating a Project

The completed app for each step of the tutorial is available on GitHub.

To get started with the Android Chat SDK, open Android Studio and create a new project.

  • Select the Empty Activity template
  • Name the project ChatTutorial
  • Set the package name to com.example.chattutorial
  • Select your language - Kotlin (recommended) or Java
  • Set the Minimum SDK to 21 (or higher)

Set up demo messaging app in Android Studio

If you are using Kotlin, make sure you're on version 1.4 or later

You can check which version of Kotlin you are using by checking this setting in your project level build.gradle file:

buildscript { // The tutorial uses features added in kotlin 1.4 ext.kotlin_version = "1.4.30" dependencies { classpath "com.android.tools.build:gradle:4.1.0" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } }
Make sure you're using a Material theme in your app

If you're using an up-to-date version of Android Studio, your newly created project should already be using a Theme.MaterialComponents theme as the parent to its app theme (you can check this in styles.xml or themes.xml). If you're running an older version, change the parent theme to be a Material theme instead of Theme.AppCompat.

If you want to keep using AppCompat theming, you can use a Bridge Theme instead.

Our SDKs are available from MavenCentral, with some of our dependencies being hosted on Jitpack. Update your repositories in the project level build.gradle file like so:

allprojects { repositories { google() mavenCentral() maven { url "https://jitpack.io" } jcenter() } }

First, we'll enable View Binding. Next, we're going to add the Stream Chat SDK and Coil to our project dependencies. Open up the app module's build.gradle script and make the following changes:

plugins { id 'com.android.application' id 'kotlin-android' } android { compileSdkVersion 30 defaultConfig { applicationId "com.example.chattutorial" minSdkVersion 21 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } // Enable ViewBinding buildFeatures { viewBinding true } } dependencies { // Add new dependencies implementation "io.getstream:stream-chat-android-ui-components:4.8.0" implementation "io.coil-kt:coil:1.1.1" implementation "androidx.activity:activity-ktx:1.2.0" implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation 'androidx.core:core-ktx:1.3.2' implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.material:material:1.3.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' }
plugins { id 'com.android.application' } android { compileSdkVersion 30 defaultConfig { applicationId "com.example.chattutorial" minSdkVersion 21 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } // Enable ViewBinding buildFeatures { viewBinding true } } dependencies { // Add new dependencies implementation "io.getstream:stream-chat-android-ui-components:4.8.0" implementation 'io.coil-kt:coil:1.1.1' implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'com.google.android.material:material:1.3.0' implementation 'androidx.constraintlayout:constraintlayout:2.0.4' testImplementation 'junit:junit:4.+' androidTestImplementation 'androidx.test.ext:junit:1.1.2' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0' }

After you edit your Gradle files, make sure to sync the project (Android Studio will prompt you for this) with the new changes.

Displaying a List of Channels

Stream provides a low-level client, an offline support library, and convenient UI components to help you quickly build your messaging interface. In this section, we'll be using the UI components to quickly display a channel list.

First, open up activity_main.xml, and change the contents of the file to the following to display a full screen ChannelListView:

<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <io.getstream.chat.android.ui.channel.list.ChannelListView android:id="@+id/channelListView" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>

Next, open up MainActivity and replace the file's contents with the following code:

package com.example.chattutorial import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.example.chattutorial.databinding.ActivityMainBinding import io.getstream.chat.android.client.ChatClient import io.getstream.chat.android.client.models.Filters import io.getstream.chat.android.client.models.User import io.getstream.chat.android.livedata.ChatDomain import io.getstream.chat.android.ui.channel.list.viewmodel.ChannelListViewModel import io.getstream.chat.android.ui.channel.list.viewmodel.bindView import io.getstream.chat.android.ui.channel.list.viewmodel.factory.ChannelListViewModelFactory class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Step 0 - inflate binding binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // Step 1 - Set up the client for API calls and the domain for offline storage val client = ChatClient.Builder("b67pax5b2wdq", applicationContext).build() ChatDomain.Builder(client, applicationContext).build() // Step 2 - Authenticate and connect the user val user = User( id = "tutorial-droid", extraData = mutableMapOf( "name" to "Tutorial Droid", "image" to "https://bit.ly/2TIt8NR", ), ) client.connectUser( user = user, token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoidHV0b3JpYWwtZHJvaWQifQ.NhEr0hP9W9nwqV7ZkdShxvi02C5PR7SJE7Cs4y7kyqg" ).enqueue() // Step 3 - Set the channel list filter and order // This can be read as requiring only channels whose "type" is "messaging" AND // whose "members" include our "user.id" val filter = Filters.and( Filters.eq("type", "messaging"), Filters.`in`("members", listOf(user.id)) ) val viewModelFactory = ChannelListViewModelFactory(filter, ChannelListViewModel.DEFAULT_SORT) val viewModel: ChannelListViewModel by viewModels { viewModelFactory } // Step 4 - Connect the ChannelListViewModel to the ChannelListView, loose // coupling makes it easy to customize // Note: the listener syntax used here requires Kotlin 1.4 viewModel.bindView(binding.channelListView, this) binding.channelListView.setChannelItemClickListener { channel -> // TODO - start channel activity } } }
package com.example.chattutorial; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProvider; import com.example.chattutorial.databinding.ActivityMainBinding; import org.jetbrains.annotations.Nullable; import io.getstream.chat.android.client.ChatClient; import io.getstream.chat.android.client.api.models.FilterObject; import io.getstream.chat.android.client.models.Filters; import io.getstream.chat.android.client.models.User; import io.getstream.chat.android.livedata.ChatDomain; import io.getstream.chat.android.ui.channel.list.viewmodel.ChannelListViewModel; import io.getstream.chat.android.ui.channel.list.viewmodel.ChannelListViewModelBinding; import io.getstream.chat.android.ui.channel.list.viewmodel.factory.ChannelListViewModelFactory; import static java.util.Collections.singletonList; public final class MainActivity extends AppCompatActivity { protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Step 0 - inflate binding ActivityMainBinding binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); // Step 1 - Set up the client for API calls and the domain for offline storage ChatClient client = new ChatClient.Builder("b67pax5b2wdq", getApplicationContext()).build(); new ChatDomain.Builder(client, getApplicationContext()).build(); // Step 2 - Authenticate and connect the user User user = new User(); user.setId("tutorial-droid"); user.getExtraData().put("name", "Tutorial Droid"); user.getExtraData().put("image", "https://bit.ly/2TIt8NR"); client.connectUser( user, "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoidHV0b3JpYWwtZHJvaWQifQ.NhEr0hP9W9nwqV7ZkdShxvi02C5PR7SJE7Cs4y7kyqg" ).enqueue(); // Step 3 - Set the channel list filter and order // This can be read as requiring only channels whose "type" is "messaging" AND // whose "members" include our "user.id" FilterObject filter = Filters.and( Filters.eq("type", "messaging"), Filters.in("members", singletonList(user.getId())) ); ChannelListViewModelFactory factory = new ChannelListViewModelFactory( filter, ChannelListViewModel.DEFAULT_SORT ); ChannelListViewModel channelsViewModel = new ViewModelProvider(this, factory).get(ChannelListViewModel.class); // Step 4 - Connect the ChannelListViewModel to the ChannelListView, loose // coupling makes it easy to customize ChannelListViewModelBinding.bind(channelsViewModel, binding.channelListView, this); binding.channelListView.setChannelItemClickListener(channel -> { // TODO - start channel activity }); } }

Channel List Chat interface for Java / Kotlin on Android

Let's have a quick look at the source code shown above:

  • Step 1: We create a connection to Stream by initializing the ChatClient using an API key. This key points to a tutorial environment, but you can sign up for a free Chat trial to get your own later. Next, we initialize the ChatDomain for the convenience of its offline storage capabilities and client interactions for data retrieval. For a production app, we recommend initializing these two classes in your Application class.
  • Step 2: We create a User instance and pass it to the ChatClient's connectUser method, along with a pre-generated user token, in order to authenticate the user. In a real-world application, your authentication backend would generate such a token at login / signup and hand it over to the mobile app. For more information, see the Tokens & Authentication page.
  • Step 3: We configure the ChannelListViewModelFactory with a filter and a sort option. We’re using the default sort option which orders the channels by last_updated_at time, putting the most recently used channels on the top. For the filter, we’re specifying all channels of type messaging where the current user is a member. The documentation about Querying Channels covers this in more detail.
  • Step 4: We bind our ChannelListView to the ChannelListViewModel by calling the bindView function.

Build and run your application - you should see the channel list interface shown on the right.

Creating a Chat Experience

Next, let's open up one of these channels and start chatting. To do this, we'll leverage the MessageListHeaderView, MessageListView, and MessageInputView components.

Although our default components provide a robust experience, it's possible to configure and customize them, or even use your own custom views.

Create a new Empty Activity (New -> Activity -> Empty Activity) and name it ChannelActivity.

Make sure that ChannelActivity is added to your manifest. Android Studio does this automatically if you use the wizard to create the Activity, but you'll need to add it yourself if you manually created the Activity class.

Open up activity_channel.xml and change the layout to the following:

<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <io.getstream.chat.android.ui.message.list.header.MessageListHeaderView android:id="@+id/messageListHeaderView" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <io.getstream.chat.android.ui.message.list.MessageListView android:id="@+id/messageListView" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toTopOf="@+id/messageInputView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/messageListHeaderView" /> <io.getstream.chat.android.ui.message.input.MessageInputView android:id="@+id/messageInputView" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>

Next, replace the code in ChannelActivity with this code:

package com.example.chattutorial import android.content.Context import android.content.Intent import android.os.Bundle import androidx.activity.addCallback import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import com.example.chattutorial.databinding.ActivityChannelBinding import com.getstream.sdk.chat.viewmodel.MessageInputViewModel import com.getstream.sdk.chat.viewmodel.messages.MessageListViewModel import com.getstream.sdk.chat.viewmodel.messages.MessageListViewModel.Mode.Normal import com.getstream.sdk.chat.viewmodel.messages.MessageListViewModel.Mode.Thread import com.getstream.sdk.chat.viewmodel.messages.MessageListViewModel.State.NavigateUp import io.getstream.chat.android.client.models.Channel import io.getstream.chat.android.ui.message.input.viewmodel.bindView import io.getstream.chat.android.ui.message.list.header.viewmodel.MessageListHeaderViewModel import io.getstream.chat.android.ui.message.list.header.viewmodel.bindView import io.getstream.chat.android.ui.message.list.viewmodel.bindView import io.getstream.chat.android.ui.message.list.viewmodel.factory.MessageListViewModelFactory class ChannelActivity : AppCompatActivity() { private lateinit var binding: ActivityChannelBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Step 0 - inflate binding binding = ActivityChannelBinding.inflate(layoutInflater) setContentView(binding.root) val cid = checkNotNull(intent.getStringExtra(CID_KEY)) { "Specifying a channel id is required when starting ChannelActivity" } // Step 1 - Create three separate ViewModels for the views so it's easy // to customize them individually val factory = MessageListViewModelFactory(cid) val messageListHeaderViewModel: MessageListHeaderViewModel by viewModels { factory } val messageListViewModel: MessageListViewModel by viewModels { factory } val messageInputViewModel: MessageInputViewModel by viewModels { factory } // TODO set custom Imgur attachment factory // Step 2 - Bind the view and ViewModels, they are loosely coupled so it's easy to customize messageListHeaderViewModel.bindView(binding.messageListHeaderView, this) messageListViewModel.bindView(binding.messageListView, this) messageInputViewModel.bindView(binding.messageInputView, this) // Step 3 - Let both MessageListHeaderView and MessageInputView know when we open a thread // Note: the observe syntax used here requires Kotlin 1.4 messageListViewModel.mode.observe(this) { mode -> when (mode) { is Thread -> { messageListHeaderViewModel.setActiveThread(mode.parentMessage) messageInputViewModel.setActiveThread(mode.parentMessage) } Normal -> { messageListHeaderViewModel.resetThread() messageInputViewModel.resetThread() } } } // Step 4 - Let the message input know when we are editing a message binding.messageListView.setMessageEditHandler { message -> messageInputViewModel.editMessage.postValue(message) } // Step 5 - Handle navigate up state messageListViewModel.state.observe(this) { state -> if (state is NavigateUp) { finish() } } // Step 6 - Handle back button behaviour correctly when you're in a thread val backHandler = { messageListViewModel.onEvent(MessageListViewModel.Event.BackButtonPressed) } binding.messageListHeaderView.setBackButtonClickListener(backHandler) onBackPressedDispatcher.addCallback(this) { backHandler() } } companion object { private const val CID_KEY = "key:cid" fun newIntent(context: Context, channel: Channel): Intent = Intent(context, ChannelActivity::class.java).putExtra(CID_KEY, channel.cid) } }
package com.example.chattutorial; import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.activity.OnBackPressedCallback; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.lifecycle.ViewModelProvider; import com.example.chattutorial.databinding.ActivityChannelBinding; import com.getstream.sdk.chat.viewmodel.MessageInputViewModel; import com.getstream.sdk.chat.viewmodel.messages.MessageListViewModel; import com.getstream.sdk.chat.viewmodel.messages.MessageListViewModel.Mode.Normal; import com.getstream.sdk.chat.viewmodel.messages.MessageListViewModel.Mode.Thread; import com.getstream.sdk.chat.viewmodel.messages.MessageListViewModel.State.NavigateUp; import io.getstream.chat.android.client.models.Channel; import io.getstream.chat.android.client.models.Message; import io.getstream.chat.android.ui.message.input.viewmodel.MessageInputViewModelBinding; import io.getstream.chat.android.ui.message.list.header.MessageListHeaderView; import io.getstream.chat.android.ui.message.list.header.viewmodel.MessageListHeaderViewModel; import io.getstream.chat.android.ui.message.list.header.viewmodel.MessageListHeaderViewModelBinding; import io.getstream.chat.android.ui.message.list.viewmodel.MessageListViewModelBinding; import io.getstream.chat.android.ui.message.list.viewmodel.factory.MessageListViewModelFactory; public class ChannelActivity extends AppCompatActivity { private final static String CID_KEY = "key:cid"; public static Intent newIntent(Context context, Channel channel) { final Intent intent = new Intent(context, ChannelActivity.class); intent.putExtra(CID_KEY, channel.getCid()); return intent; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Step 0 - inflate binding ActivityChannelBinding binding = ActivityChannelBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); String cid = getIntent().getStringExtra(CID_KEY); if (cid == null) { throw new IllegalStateException("Specifying a channel id is required when starting ChannelActivity"); } // Step 1 - Create three separate ViewModels for the views so it's easy // to customize them individually MessageListViewModelFactory factory = new MessageListViewModelFactory(cid); ViewModelProvider provider = new ViewModelProvider(this, factory); MessageListHeaderViewModel messageListHeaderViewModel = provider.get(MessageListHeaderViewModel.class); MessageListViewModel messageListViewModel = provider.get(MessageListViewModel.class); MessageInputViewModel messageInputViewModel = provider.get(MessageInputViewModel.class); // TODO set custom Imgur attachment factory // Step 2 - Bind the view and ViewModels, they are loosely coupled so it's easy to customize MessageListHeaderViewModelBinding.bind(messageListHeaderViewModel, binding.messageListHeaderView, this); MessageListViewModelBinding.bind(messageListViewModel, binding.messageListView, this); MessageInputViewModelBinding.bind(messageInputViewModel, binding.messageInputView, this); // Step 3 - Let both message list header and message input know when we open a thread messageListViewModel.getMode().observe(this, mode -> { if (mode instanceof Thread) { Message parentMessage = ((Thread) mode).getParentMessage(); messageListHeaderViewModel.setActiveThread(parentMessage); messageInputViewModel.setActiveThread(parentMessage); } else if (mode instanceof Normal) { messageListHeaderViewModel.resetThread(); messageInputViewModel.resetThread(); } }); // Step 4 - Let the message input know when we are editing a message binding.messageListView.setMessageEditHandler(message -> { messageInputViewModel.getEditMessage().postValue(message); }); // Step 5 - Handle navigate up state messageListViewModel.getState().observe(this, state -> { if (state instanceof NavigateUp) { finish(); } }); // Step 6 - Handle back button behaviour correctly when you're in a thread MessageListHeaderView.OnClickListener backHandler = () -> { messageListViewModel.onEvent(MessageListViewModel.Event.BackButtonPressed.INSTANCE); }; binding.messageListHeaderView.setBackButtonClickListener(backHandler); getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) { @Override public void handleOnBackPressed() { backHandler.onClick(); } }); } }

Configuring ChannelActivity involves a few steps, so let's review what's going on.

  • Step 1: We set up three ViewModels:
  • Step 2: We bind these ViewModels to their respective Views. This loose coupling between components makes it easy to customize things, or only use the components you find necessary.
  • Steps 3 and 4: We coordinate the MessageListView with both MessageListHeaderView and MessageInputView. The MessageInputView needs to know when you’re editing a message or when you enter a message thread, which is also a piece of useful information for MessageListHeaderView.
  • Steps 5 and 6: We create a back button handler, and set the same behavior for the MessageListHeaderView and the Activity's OnBackPressedDispatcher. The handler sends a BackButtonPressed event to the MessageListViewModel, which will decide how to handle this event. If we're in a message thread, it'll navigate back to the channel. If we're already in the channel, it will navigate to the channel list by emitting a NavigateUp state that we handle by finishing `ChannelActivity``.

Message List Chat interface for Java / Kotlin on Android

Lastly, we want to launch ChannelActivity when you tap a channel in the channel list. Open MainActivity and replace the TODO at the end of the onCreate method`:

binding.channelListView.setChannelItemClickListener { channel -> startActivity(ChannelActivity.newIntent(this, channel)) }
binding.channelListView.setChannelItemClickListener( channel -> startActivity(ChannelActivity.newIntent(this, channel)) );

If you run the application and tap on a channel, you'll now see the chat interface shown on the right.

Chat Features

Congrats on getting your chat experience up and running! Stream Chat provides you with all the features you need to build an engaging messaging experience:

  1. Offline support: send messages, edit messages and send reactions while offline
  2. Link previews: generated automatically when you send a link
  3. Commands: type / to use commands like /giphy
  4. Reactions: long-press on a messages to add a reaction
  5. Attachments: use the paperclip button in MessageInputView to attach images and files
  6. Edit message: long-press on your message for message options, including editing
  7. Threads: start message threads to reply to any message

You should also notice that, regardless of whether you chose to develop your app in Kotlin or Java, the chat loads very quickly. Stream’s API is powered by Go, RocksDB and Raft. The API tends to respond in less than 10ms and powers activity feeds and chat for over a billion end users.

Some of the features are hard to see in action with just one user online. You can open the same channel on the web and try user-to-user interactions like typing events, reactions, and threads.

Chat Message Customization

You now have a fully functional mobile chat interface. Not bad for a couple minutes of work! Maybe you'd like to change things up a bit though? No problem! Here are four ways to customize your chat experience:

Customized Green Message List Chat interface for Java / Kotlin on Android

  1. Style the MessageListView using attributes (easy)
  2. Create a custom attachment view (easy)
  3. Build your own views on top of the LiveData objects provided by the offline support library (advanced)
  4. Use the low level client to directly interact with the API

In the next sections, we'll show an example for each type of customization. We'll start by changing the colors of the chat messages to match your theme.

Open activity_channel.xml and customize the MessageListView with the following attributes for a green message style:

<io.getstream.chat.android.ui.message.list.MessageListView android:id="@+id/messageListView" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toTopOf="@+id/messageInputView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/messageListHeaderView" app:streamUiMessageBackgroundColorMine="#70AF74" app:streamUiMessageBackgroundColorTheirs="#FFFFFF" app:streamUiMessageTextColorMine="#FFFFFF" app:streamUiMessageTextColorTheirs="#000000" />

If you run the app and write a message, you'll notice that messages written by you are now green. The documentation for MessageListView details all the available customization options.

Creating Custom Attachment Views

There may come a time when you have requirements to include things in your chat experience that we don't provide out-of-the-box. For times like this, we provide two main customization paths: you can either reimplement the entire ViewHolder and display a message how you like, or you can use custom attachment views, which is a lot less work. We'll look at this latter approach now.

You could use this to embed a shopping cart in your chat, share a location, or perhaps implement a poll. For this example, we'll keep it simple and customize the preview for images shared from Imgur. We're going to render the Imgur logo over images from the imgur.com domain.

As a first step, download the Imgur logo and add it to your drawable folder.

The Imgur logo

Next, create a new layout file called attachment_imgur.xml:

<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content"> <com.google.android.material.imageview.ShapeableImageView android:id="@+id/iv_media_thumb" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_marginStart="8dp" android:layout_marginTop="4dp" android:layout_marginEnd="8dp" android:scaleType="centerCrop" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintDimensionRatio="h,1:1" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ImageView android:id="@+id/logo" android:layout_width="150dp" android:layout_height="50dp" android:background="@drawable/imgur_logo" app:layout_constraintBottom_toBottomOf="@id/iv_media_thumb" app:layout_constraintEnd_toEndOf="@+id/iv_media_thumb" app:layout_constraintStart_toStartOf="@id/iv_media_thumb" app:layout_constraintTop_toTopOf="@id/iv_media_thumb" /> </androidx.constraintlayout.widget.ConstraintLayout>

Now we need to create a custom implementation of AttachmentViewFactory. Create a new file called ImgurAttachmentViewFactory and add this code:

package com.example.chattutorial import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import coil.load import com.example.chattutorial.databinding.AttachmentImgurBinding import com.getstream.sdk.chat.adapter.MessageListItem import io.getstream.chat.android.client.models.Attachment import io.getstream.chat.android.ui.message.list.adapter.MessageListListenerContainer import io.getstream.chat.android.ui.message.list.adapter.viewholder.attachment.AttachmentViewFactory import io.getstream.chat.android.ui.message.list.MessageListItemStyle class ImgurAttachmentViewFactory : AttachmentViewFactory() { override fun createAttachmentView( data: MessageListItem.MessageItem, listeners: MessageListListenerContainer, style: MessageListItemStyle, parent: ViewGroup, ): View { val imgurAttachment = data.message.attachments.firstOrNull { it.isImgurAttachment() } return when { imgurAttachment != null -> createImgurAttachmentView(imgurAttachment, parent) else -> super.createAttachmentView(data, listeners, style, parent) } } private fun Attachment.isImgurAttachment(): Boolean = imageUrl?.contains("imgur") == true private fun createImgurAttachmentView(imgurAttachment: Attachment, parent: ViewGroup): View { val binding = AttachmentImgurBinding .inflate(LayoutInflater.from(parent.context), null, false) binding.ivMediaThumb.apply { shapeAppearanceModel = shapeAppearanceModel .toBuilder() .setAllCornerSizes(resources.getDimension(R.dimen.stream_ui_selected_attachment_corner_radius)) .build() load(imgurAttachment.imageUrl) { allowHardware(false) crossfade(true) placeholder(R.drawable.stream_ui_picture_placeholder) } } return binding.root } }
package com.example.chattutorial; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.chattutorial.databinding.AttachmentImgurBinding; import com.getstream.sdk.chat.adapter.MessageListItem; import com.google.android.material.shape.ShapeAppearanceModel; import org.jetbrains.annotations.NotNull; import coil.Coil; import coil.request.ImageRequest; import io.getstream.chat.android.client.models.Attachment; import io.getstream.chat.android.ui.message.list.adapter.MessageListListenerContainer; import io.getstream.chat.android.ui.message.list.adapter.viewholder.attachment.AttachmentViewFactory; import io.getstream.chat.android.ui.message.list.MessageListItemStyle; public class ImgurAttachmentViewFactory extends AttachmentViewFactory { @NotNull @Override public View createAttachmentView(@NotNull MessageListItem.MessageItem data, @NotNull MessageListListenerContainer listeners, @NotNull MessageListItemStyle style, @NotNull ViewGroup parent) { Attachment imgurAttachment = null; for (Attachment attachment : data.getMessage().getAttachments()) { String imageUrl = attachment.getImageUrl(); if (imageUrl != null && imageUrl.contains("imgur")) { imgurAttachment = attachment; break; } } if (imgurAttachment != null) { return createImgurAttachmentView(imgurAttachment, parent); } else { return super.createAttachmentView(data, listeners, style, parent); } } private View createImgurAttachmentView(Attachment imgurAttachment, ViewGroup parent) { AttachmentImgurBinding binding = AttachmentImgurBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false); float cornerRadius = binding.getRoot() .getResources() .getDimension(R.dimen.stream_ui_selected_attachment_corner_radius); ShapeAppearanceModel model = binding.ivMediaThumb.getShapeAppearanceModel() .toBuilder() .setAllCornerSizes(cornerRadius) .build(); binding.ivMediaThumb.setShapeAppearanceModel(model); ImageRequest imageRequest = new ImageRequest.Builder(parent.getContext()) .data(imgurAttachment.getImageUrl()) .allowHardware(false) .crossfade(true) .placeholder(R.drawable.stream_ui_picture_placeholder) .target(binding.ivMediaThumb) .build(); Coil.imageLoader(parent.getContext()).enqueue(imageRequest); return binding.getRoot(); } }

Let's break down what we're doing above:

  1. In createAttachmentView, we check whether there's an Imgur attachment on the current message. Link previews in the Chat SDK are added to the message as attachments.
  2. If there is an Imgur attachment on the current message, createImgurAttachmentView inflates the layout defined earlier, adds some styling (rounded corners), and then loads the Imgur image from the attachment's URL into the contained ImageView. We return this newly created View from the factory, and it'll be added to the message's UI.
  3. If we didn't find an Imgur attachment, we call the default implementation of createAttachmentView in the base factory class, which will render images, files, and link previews with the SDK's built-in UI.

Finally, we'll provide an instance of this ImgurAttachmentViewFactory to the MessageListView component. Open ChannelActivity and replace the TODO comment with the following:

// Set view factory for Imgur attachments binding.messageListView.setAttachmentViewFactory(ImgurAttachmentViewFactory())
// Set view factory for Imgur attachments binding.messageListView.setAttachmentViewFactory(new ImgurAttachmentViewFactory());

Your Custom Attachment View

Imgur Logo overlay on the in-app messaging chat interface

When you run your app, you should now see the Imgur logo displayed over images from Imgur. You can test this by posting an Imgur link like this one: https://imgur.com/gallery/ro2nIC6

This was, of course, a very simple change, but you could use the same approach to implement a product preview, shopping cart, location sharing, polls, and more. You can achieve lots of your message customization goals by implementing a custom attachment View.

If you need even more customization, you can also implement custom ViewHolders for the entire message object.

Creating a Typing Status Component

If you want to build a custom UI, you can do that using the LiveData objects provided by our offline support library, or the events provided by our low level client. The example below will show you how to build a custom typing status component using both approaches.

First, open activity_channel.xml and add the following TextView above the MessageListView. You'll also want to update the constraints for the MessageListView.

<TextView android:id="@+id/typingHeaderView" android:layout_width="0dp" android:layout_height="31dp" android:background="#DDD" android:gravity="center" android:textColor="@color/black" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/messageListHeaderView" /> <io.getstream.chat.android.ui.message.list.MessageListView android:id="@+id/messageListView" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toTopOf="@+id/messageInputView" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/typingHeaderView" />

Option 1 - Typing Status Using the Offline Library

In-app example of typing indicator on an Android messaging window

The offline support library contains the ChatDomain class, which provides observable LiveData objects for a channel such as messages, typing state, reads statuses, etc. The full list of LiveData objects provided is detailed in the documentation. These make it easy to obtain data for use in your own custom UI.

Open ChannelActivity and add the following code below Step 6, still within the onCreate method:

// Custom typing info header bar val nobodyTyping = "nobody is typing" binding.typingHeaderView.text = nobodyTyping // Obtain a ChannelController ChatDomain .instance() .useCases .getChannelController(cid) .enqueue { channelControllerResult -> if (channelControllerResult.isSuccess) { // Observe typing users channelControllerResult.data().typing.observe(this) { typingState -> binding.typingHeaderView.text = when { typingState.users.isNotEmpty() -> { typingState.users.joinToString(prefix = "typing: ") { user -> user.name } } else -> nobodyTyping } } } }
// Custom typing info header bar TextView typingHeaderView = findViewById(R.id.typingHeaderView); String nobodyTyping = "nobody is typing"; typingHeaderView.setText(nobodyTyping); // Obtain a ChannelController ChatDomain.instance() .getUseCases() .getGetChannelController() .invoke(cid) .enqueue((result) -> { ChannelController channelController = result.data(); // Observe typing users channelController.getTyping().observe(this, typingState -> { if (typingState.getUsers().isEmpty()) { typingHeaderView.setText(nobodyTyping); } else { List<String> userNames = new LinkedList<>(); for (User user : typingState.getUsers()) { userNames.add((String) user.getExtraData().get("name")); } String typing = "typing: " + TextUtils.join(", ", userNames); typingHeaderView.setText(typing); } }); });

Remember to update your imports before running the app. You should now see a small typing indicator bar just below the channel header. Note that the current user is excluded from the list of typing users.

The code is quite simple - we are invoking the getChannelController use case which returns the ChannelController. The controller exposes a LiveData object, typing, for observing typing users. We observe this and update the text in the TextView we've added.

To test the behaviour, you can open a client on the web, enter the same channel, and then type away!

Option 2 - Typing Status Using the Low-Level Client

In-app example of typing into an Android messaging window

The low-level client enables you to talk directly to Stream's API. This gives you the flexibility to implement any messaging UI that you want. In this case, we want to show who is typing, current user included.

The entry point for the low-level client's APIs is the ChatClient class. In the code below, we get the ChatClient instance, and fetch a ChannelClient using the the channel(cid) call. This provides access to all operations on the given channel.

Then, we use subscribeFor to listen to all TypingStart and TypingStop events in the current channel, and update the contents of the TextView with the list of typing users. Note that we specify the current Activity as the lifecycle owner to ensure that the event callbacks are removed when the Activity is no longer active.

// Custom typing info header bar val nobodyTyping = "nobody is typing" binding.typingHeaderView.text = nobodyTyping val currentlyTyping = mutableSetOf<String>() // Observe raw events through the low-level client ChatClient .instance() .channel(cid) .subscribeFor( this, TypingStartEvent::class, TypingStopEvent::class ) { event -> when (event) { is TypingStartEvent -> currentlyTyping.add(event.user.name) is TypingStopEvent -> currentlyTyping.remove(event.user.name) } binding.typingHeaderView.text = when { currentlyTyping.isNotEmpty() -> currentlyTyping.joinToString(prefix = "typing: ") else -> nobodyTyping } }
// Custom typing info header bar TextView typingHeaderView = findViewById(R.id.typingHeaderView); String nobodyTyping = "nobody is typing"; typingHeaderView.setText(nobodyTyping); // Observe raw events through the low-level client Set<String> currentlyTyping = new HashSet<>(); ChatClient.instance() .channel(cid) .subscribeFor( this, new Class[]{TypingStartEvent.class, TypingStopEvent.class}, event -> { if (event instanceof TypingStartEvent) { User user = ((TypingStartEvent) event).getUser(); String name = (String) user.getExtraData().get("name"); currentlyTyping.add(name); } else if (event instanceof TypingStopEvent) { User user = ((TypingStopEvent) event).getUser(); String name = (String) user.getExtraData().get("name"); currentlyTyping.remove(name); } String typing = "nobody is typing"; if (!currentlyTyping.isEmpty()) { typing = "typing: " + TextUtils.join(", ", currentlyTyping); } typingHeaderView.setText(typing); } );

Run your app and start typing in the MessageInputView: you'll notice that the typing header on top updates to show that the current user is typing.

You can also use a web client to enter the same channel and generate typing events.

Congratulations!

In this Android in-app messaging tutorial, you learned how to build a fully functional chat app using Java or Kotlin. You also learned how easy it is to customize the behavior and build any type of chat or messaging experience.

Remember, you can also check out the completed app for the tutorial on GitHub.

If you want to get started on integrating chat into your own app, sign up for a free Chat trial, and get your own API key to build with!

To recap, our Android Chat SDK consists of three libraries which give you an opportunity to interact with Stream Chat APIs on a different level:

  • stream-chat-android-client - The official low-level Android SDK for Stream Chat. It allows you to make API calls and receive events whenever something changes on a user or channel that you’re watching.
  • stream-chat-android-offline - Builds on top of the low level client, adds seamless offline support, optimistic UI updates (great for performance) and exposes LiveData objects. If you want to build a fully custom UI, this library is your best starting point.
  • stream-chat-android-ui-components - Provides ready-to-use UI components while also taking advantage of the offline library and low level SDK. This allows you to ship chat in your application in a matter of days.

The underlying chat API is based on Go, RocksDB, and Raft. This makes the chat experience extremely fast with response times that are often below 10ms.

Final Thoughts

In this chat app tutorial we built a fully functioning Android messaging app with our Android SDK component library. We also showed how easy it is to customize the behavior and the style of the Android chat app components with minimal code changes.

Both the chat SDK for Android and the API have plenty more features available to support more advanced use-cases such as push notifications, content moderation, rich messages and more. Please check out our Flutter tutorial too. If you want some inspiration for your app, download our free chat interface UI kit.

Give us Feedback!

Did you find this tutorial helpful in getting you up and running with Android for adding chat to your project? Either good or bad, we’re looking for your honest feedback so we can improve.