ListView implements chat conversation

Posted by draco2317 on Sat, 27 Nov 2021 04:37:55 +0100

When I first came into contact with ListView, I always saw others make a lot of strange interfaces, but I just couldn't. then I learned to customize the View, thinking that ListView can also customize the desired style, and then collected a lot of methods on the Internet, either I can't understand it, the code has not been copied yet, or it's not the one I want. The ListView control used here today does not need to be customized, e but can be completed by using the ListView's own control.

The well-known QQ and wechat interfaces will display at least two interfaces. There are pages for both sides to send messages. As long as you are diligent, I believe that if you read my method today, you can add more than two layouts on ListView. The teacher won't tell you. The teacher just introduces you to understand the program, understand the program and write the program. What you need to improve other skills is to constantly ask questions, ask questions to others and answer other people's questions. In this way, you will get a lot of answers.

One difference from the ListView we usually use is that it has two different layouts - the received layout and the sent layout. If you need to achieve such an effect, you must start with the Adapter. When defining the BaseAdapter, you need to override the getView() method. Just judge which layout you want, ListView has taken this situation into account when designing, so it provides two methods.

public int getItemView(int position){}     What type of item is returned for position

public   int getViewTypeCount(){}; Returns the total number of different layouts

1. Renderings

 

  2 design two layout files, the so-called receiving layout and sending layout. Because the two layout files are basically the same, the difference is only the location of the controls, and the orientation of the actual pictures. Please select the Jiugong picture to adapt the pictures. Only one layout file is listed here

<?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="horizontal"
    android:gravity="center_vertical"
    android:padding="10dp">

    <ImageView
        android:id="@+id/icon_in"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/ic_launcher_background"/>
    <TextView
        android:id="@+id/text_in"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textSize="20sp"
        android:textColor="#DF0606"
        android:gravity="center"
        android:background="@drawable/popoleft"
        android:text="Open the work order, and all major brands open the electric rice cooker of Dong Pengfei's water and electricity holding electric rice cooker"/>
</LinearLayout>

3. Chat content is easy to obtain objects in the Adapter. We need to encapsulate a javaBean object to save chat record information

package com.example.demod6;

import android.graphics.Bitmap;

public class ChatItemListViewBean {
    private int type;
    private String text;
    private Bitmap icon;

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public Bitmap getIcon() {
        return icon;
    }

    public void setIcon(Bitmap icon) {
        this.icon = icon;
    }
}

4 the most important is the BaseAdapter class, which also uses the ViewHolder mode to improve the efficiency of ListView, and judges the layout type in the getView() method to determine which layout to use.

package com.example.demod6;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class ViewHolderView extends BaseAdapter {
    private List<ChatItemListViewBean> mData;
    private LayoutInflater inflater;

    public ViewHolderView(List<ChatItemListViewBean> mData, Context context) {
        this.mData = mData;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public Object getItem(int i) {
        return mData.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View contentView, ViewGroup viewGroup) {
        ViewHolder holder = null;
        if(contentView == null){
            if(getItemViewType(position) == 0){
                holder = new ViewHolder();
                contentView = inflater.inflate(R.layout.chat_item_in,null);
                holder.imageView = (ImageView) contentView.findViewById(R.id.icon_in);
                holder.title = (TextView) contentView.findViewById(R.id.text_in);
            }else {
                holder = new ViewHolder();
                contentView = inflater.inflate(R.layout.chat_item_out,null);
                holder.imageView = (ImageView) contentView.findViewById(R.id.icon_in);
                holder.title = (TextView) contentView.findViewById(R.id.text_in);
            }
            contentView.setTag(holder);
        }else {
            holder = (ViewHolder) contentView.getTag();//Find objects through tag cache
        }
        holder.imageView.setImageBitmap(mData.get(position).getIcon());
        holder.title.setText(mData.get(position).getText());
        return contentView;
    }

    @Override
    public int getViewTypeCount() { //What is the type of return position

        return 2;
    }

    @Override
    public int getItemViewType(int position) { //Returns the total number of different layouts
        ChatItemListViewBean bean = mData.get(position);
        return bean.getType();
    }

    public class ViewHolder{
        public ImageView imageView;
        public TextView title;
    }
}

6 to implement multiple layouts in ListView, you need to add some test code

package com.example.demod6;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.animation.ObjectAnimator;
import android.app.ActionBar;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.TextView;

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

public class MainActivity extends AppCompatActivity {

    private List<ChatItemListViewBean> mData = new ArrayList<ChatItemListViewBean>();
    private int mTouchSlop;
    private  TextView header;
    private TextView toolBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolBar = (TextView) findViewById(R.id.img);

        MyListView myListView = (MyListView) findViewById(R.id.listView);
       initListView();
        ViewHolderView adapter = new ViewHolderView(mData,this);
        myListView.setAdapter(adapter);

//        header = new View(this);
        header = new TextView(this);
        header.setText("Congratulations on becoming good friends with Cheng liaoliao today");
        header.setTextColor(Color.GREEN);
        header.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        header.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, (int) getResources().getDimension(R.dimen.height)));
        myListView.addHeaderView(header); //Title header
        mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop(); //Minimum sliding distance

        //toolBar = getActionBar();

        myListView.setOnTouchListener(myTouchListenner);
    }

    private void initListView() {
        ChatItemListViewBean bean1 = new ChatItemListViewBean();
        bean1.setIcon(BitmapFactory.decodeResource(getResources(),R.drawable.m1));
        bean1.setType(0);
        bean1.setText("Hi, Hello, I'm here XXXX I saw your post on the website. Are you single?");

        ChatItemListViewBean bean2 = new ChatItemListViewBean();
        bean2.setIcon(BitmapFactory.decodeResource(getResources(),R.drawable.m2));
        bean2.setType(1);
        bean2.setText("Yeah? What does this have to do with you.");

        ChatItemListViewBean bean3 = new ChatItemListViewBean();
        bean3.setIcon(BitmapFactory.decodeResource(getResources(),R.drawable.m1));
        bean3.setType(0);
        bean3.setText("Well, I happen to be alone. I think you have good conditions and are interested in rice.");

        ChatItemListViewBean bean4 = new ChatItemListViewBean();
        bean4.setIcon(BitmapFactory.decodeResource(getResources(),R.drawable.m2));
        bean4.setType(1);
        bean4.setText("My conditions are really as you said, very good.");

        ChatItemListViewBean bean5 = new ChatItemListViewBean();
        bean5.setIcon(BitmapFactory.decodeResource(getResources(),R.drawable.m1));
        bean5.setType(0);
        bean5.setText("I am a migrant worker. Recently, my family always urges me to get married. The one introduced by my family is that I don't like it at all. I'm very helpless to work here in Shenzhen.");

        ChatItemListViewBean bean6 = new ChatItemListViewBean();
        bean6.setIcon(BitmapFactory.decodeResource(getResources(),R.drawable.m2));
        bean6.setType(1);
        bean6.setText("What do you do?");

        ChatItemListViewBean bean7 = new ChatItemListViewBean();
        bean7.setIcon(BitmapFactory.decodeResource(getResources(),R.drawable.m1));
        bean7.setType(0);
        bean7.setText("I was fired by my boss the day before yesterday. It wasn't because of something at home. As a result, I lost my job and was fined");

        ChatItemListViewBean bean8 = new ChatItemListViewBean();
        bean8.setIcon(BitmapFactory.decodeResource(getResources(),R.drawable.m2));
        bean8.setType(1);
        bean8.setText("It looks terrible. Are you going back? Or keep looking for a new job?");

        ChatItemListViewBean bean9 = new ChatItemListViewBean();
        bean9.setIcon(BitmapFactory.decodeResource(getResources(),R.drawable.m1));
        bean9.setType(0);
        bean9.setText("Hey! How to put it? I went to the talent market to find a job the day before yesterday, but I lost my money. Now I only pay attention to eating. It's pretty good here. I'll be fine when I find a job.");

        ChatItemListViewBean bean10 = new ChatItemListViewBean();
        bean10.setIcon(BitmapFactory.decodeResource(getResources(),R.drawable.m2));
        bean10.setType(1);
        bean10.setText("Where is your home? Why don't you go home and come out after a while");

        ChatItemListViewBean bean11 = new ChatItemListViewBean();
        bean11.setIcon(BitmapFactory.decodeResource(getResources(),R.drawable.m1));
        bean11.setType(0);
        bean11.setText("I don't have enough money to go home, but it can last for a while. I'm going to a factory for an interview in the afternoon. Probably at work.");

        mData.add(bean1);
        mData.add(bean2);
        mData.add(bean3);
        mData.add(bean4);
        mData.add(bean5);
        mData.add(bean6);
        mData.add(bean7);
        mData.add(bean8);
        mData.add(bean9);
        mData.add(bean10);
        mData.add(bean11);

    }

    private int mFirstY = 0;
    private int currentY = 0;
    private int direction = 0;
    private boolean mShow = true;
    private ObjectAnimator mAnimator;
View.OnTouchListener myTouchListenner = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, @NonNull MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                mFirstY = (int) event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                currentY = (int) event.getY();
                if(currentY - mFirstY > mTouchSlop){
                    direction = 0; //down
                }else if(mFirstY - currentY > mTouchSlop ){
                    direction = 1; //Up
                }
                if(direction == 1){
                    if(mShow){
                        //header.setVisibility(View.GONE);
                        toolBarAnima(0);
                        mShow = !mShow;
                    }
                }else if(direction == 0){
                    if(!mShow){
                        //header.setVisibility(View.VISIBLE);
                        toolBarAnima(1);
                        mShow = !mShow;
                    }
                }
                break;
        }
        return false;
    }
};
    /**
     * animation
     * @param flag
     */
    private void toolBarAnima(int flag){
        if(mAnimator != null && mAnimator.isRunning()){
            mAnimator.cancel();
        }
        if(flag == 0){
            mAnimator = ObjectAnimator.ofFloat(toolBar,"translationY",toolBar.getTranslationY(),0);
        }else {
            mAnimator = ObjectAnimator.ofFloat(toolBar,"translationY",toolBar.getTranslationY(),-toolBar.getHeight());
        }
        mAnimator.start();
    }
}

It's easy to finish the simulated dialogue. Come and have a try.

Topics: Android Android Studio android-studio