Last updated on August 17th, 2019 at 04:43 pm

Chat application is very popular in mobile today. In this post, I explain to you how to create a simple mobile chat application like WhatsApp, facebook messenger app. In this post, I mainly focus on how to design chat application and how its work this is simple application I did not save data to a server or anywhere but explain how you can get all that thing work and design. Before you get started you need to know about listview and how we can create a custom view and inflate view in list view. To learn about listview you follow my last post about Listview

 

Android Studio : Chat Application Download

Chat Application Android

Step 1. Create new Android application project in your Android Studio or in Eclipse.

Step 2. Now first we create a layout where we can display chat messages. First open your main xml file, I have activity_main.xml inside res folder. Open it and add Listview, Edittext and Button. I am using LinearLayout to make my design fit to every screen and adjust itself automatically.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#efefef"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/msgview"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="@null"
        android:divider="@null"
        android:stackFromBottom="true"
        android:transcriptMode="alwaysScroll"></ListView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="3">

        <EditText
            android:id="@+id/msg"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="2" />

        <Button
            android:id="@+id/send"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:text="Send" />

    </LinearLayout>
</LinearLayout>

Step 3. Now i need to create two more activity file which show message in left and right direction.

left.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/msgr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:layout_marginBottom="5dp"
        android:layout_marginRight="20dp"
        android:background="@drawable/textview"
        android:paddingBottom="8dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp"
        android:text="Sampleleft"
        android:textColor="#000" />
</RelativeLayout>

right.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/msgr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="20dp"
        android:background="@drawable/textview"
        android:paddingBottom="5dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp"
        android:text="Sample"
        android:textColor="#000" />
</LinearLayout>

Now i create a round shape file for my Textview and save file inside drawable folder with this name textview.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <stroke
                android:width="1dp"
                android:color="#CECECE" />

            <solid android:color="#DDDBDB" />

            <padding
                android:bottom="2dp"
                android:left="5dp"
                android:right="5dp"
                android:top="2dp" />

            <corners android:radius="8dp" />
        </shape>
    </item>
</layer-list>

Now our chat application design is ready to use. This is a very simple but you add more here according to your need.

Step 4. Now open your MainActivity.java  file and the following.

package trinitytuts.chatapplication;

import android.app.Activity;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;


public class MainActivity extends Activity {
    private static final String TAG = "ChatActivity";

    private ChatArrayAdapter chatArrayAdapter;
    private ListView listView;
    private EditText chatText;
    private Button buttonSend;
    private boolean side = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        buttonSend = (Button) findViewById(R.id.send);

        listView = (ListView) findViewById(R.id.msgview);

        chatArrayAdapter = new ChatArrayAdapter(getApplicationContext(), R.layout.right);
        listView.setAdapter(chatArrayAdapter);

        chatText = (EditText) findViewById(R.id.msg);
        chatText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    return sendChatMessage();
                }
                return false;
            }
        });
        buttonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                sendChatMessage();
            }
        });

        listView.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
        listView.setAdapter(chatArrayAdapter);

        //to scroll the list view to bottom on data change
        chatArrayAdapter.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
                listView.setSelection(chatArrayAdapter.getCount() - 1);
            }
        });
    }

    private boolean sendChatMessage() {
        chatArrayAdapter.add(new ChatMessage(side, chatText.getText().toString()));
        chatText.setText("");
        side = !side;
        return true;
    }
}

In above code i create a custom ArrayAdapter through this set data in my custom layout and also load specific layout.

    private boolean sendChatMessage() {
        chatArrayAdapter.add(new ChatMessage(side, chatText.getText().toString()));
        chatText.setText("");
        side = !side;
        return true;
    }

I create sendChatMessage() method in above code in this i pass two thing first is side which tell who make this message and second msg text.

I also create a class to set direction and message and call inside my customArrrayAdapter as shown above.

package trinitytuts.chatapplication;

/**
 * Created by Zeta Apponomics 3 on 24-11-2014.
 */
public class ChatMessage {
    public boolean left;
    public String message;

    public ChatMessage(boolean left, String message) {
        super();
        this.left = left;
        this.message = message;
    }
}

ChatArrayAdapter.java

package trinitytuts.chatapplication;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

class ChatArrayAdapter extends ArrayAdapter<ChatMessage> {

    private TextView chatText;
    private List<ChatMessage> chatMessageList = new ArrayList<ChatMessage>();
    private Context context;

    @Override
    public void add(ChatMessage object) {
        chatMessageList.add(object);
        super.add(object);
    }

    public ChatArrayAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
        this.context = context;
    }

    public int getCount() {
        return this.chatMessageList.size();
    }

    public ChatMessage getItem(int index) {
        return this.chatMessageList.get(index);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ChatMessage chatMessageObj = getItem(position);
        View row = convertView;
        LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (chatMessageObj.left) {
            row = inflater.inflate(R.layout.right, parent, false);
        }else{
            row = inflater.inflate(R.layout.left, parent, false);
        }
        chatText = (TextView) row.findViewById(R.id.msgr);
        chatText.setText(chatMessageObj.message);
        return row;
    }
}

this is my main class which does all work you need to load data from service and set that data in listview.

If this post help you please like TrinityTuts page and share blog with others 🙂