AndroidStudio编写界面的最佳实践

1、创建UIBestPractice项目
2、制作message_left.png 与 message_right.png两张气泡对话的图片(制作步骤https://blog.csdn.net/weixin_43880133/article/details/96966652)

编写精美的聊天界面

1、由于等会有Recycler View,所以需要在app/build.gradle当中添加依赖库,如下所示:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.android.support:recyclerview-v7:29.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

2、接下来编写主界面,主界面的修改是在activity_main.xml代码中进行

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

    android:background="#d8e0e8"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id = "@+id/msg_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/input_text"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="type something here"
            android:maxLines="2"/>
        <Button
            android:id="@+id/send"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="send"/>
    </LinearLayout>

在主界面中放置了一个RecyclerView用于显示聊天的消息内容,又放置了一个EditText用于输入消息,一个Button用于发送消息
3、定义消息的实体类,新建Msg

package com.example.uibestpratice;
//Msg类中只有两个字段,content表示消息的内容,type表示消息的类型(TYPE_RECEIVED,TYPE_SENT)
public class Msg {
    public String content;
    public int type;
    public static final int TYPE_RECEIVED=0;
    public static final int TYPE_SEND = 1;
    public Msg(String content,int type){
        this.content = content;
        this.type  = type;
  =  }
    public String getContent(){
        return content;
    }
    public int getType(){
        return type;
    }
}

public String content---->this.content有效,而 public static String content—>this.concent是无效的
4、编写RecyclerView子项的布局

<?xml version="1.0" encoding="utf-8"?>
    <!--//让收到的消息左对齐,发出的消息右对齐,并且分别使用message_left.png,和message_right.png作背景图
      这时,收到的消息和发送的消息是在同一个布局里面,但是根据可见属性,我们可以在代码中根据消息类型来决定隐藏和显示哪种消息就可以

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp">

    <LinearLayout
        android:id="@+id/left_layout"
        android:layout_width="174dp"
        android:layout_height="54dp"
        android:layout_gravity="left"
        android:background="@mipmap/message_left">

        <TextView
            android:id="@+id/left_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="10dp"
            android:textColor="#fff" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/right_layout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:background="@mipmap/message_right">

        <TextView
            android:id="@+id/right_msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="10dp" />

    </LinearLayout>

</LinearLayout>

5、创建RecyclerView的适配器类,新建类MsgAdapter
代码的编写方式和RecyclerView使用方法(一)(二)(三)基本一致,只是在onBindViewHoldder()方法中增加了对消息类型的判断,如果消息是收到的,则显示左边的布局,如果是发送的,则显示右边的消息布局

package com.example.uibestpratice;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
//需要为RecyclerView准备一个适配器,新建MsgAdapter类,让这个适配器继承自RecyclerView.Adapter,
//并将泛型指向MsgAdapter.ViewHolder,其中,ViewHolder是定义的一内部类


public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {
    private List<Msg> mMsgList;
    static class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout leftLayout;
        LinearLayout rightLayout;
        TextView leftMsg;
        TextView rightMsg;

        public ViewHolder(View view) {
            super(view);//传入一个view参数,这个参数通常是RrcycleView子项的最外层布局,
            //那么我们就可以通过findViewById()方法来获得布局中的LinearLayout和TextView的实例了
            leftLayout = (LinearLayout) view.findViewById(R.id.left_layout);
            rightLayout = (LinearLayout) view.findViewById(R.id.right_layout);
            leftMsg = (TextView) view.findViewById(R.id.left_msg);
            rightMsg = (TextView) view.findViewById(R.id.right_msg);

        }
    }
    public MsgAdapter(List<Msg> msgList){
        //此构造方法是用于吧要展示的数据源传进来并且赋值给一个全局变量mMsgAdapter
        //后续的操作是在这个数据源上进行
            mMsgList = msgList;
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType){
        //此方法是创建ViewHolder实例,我们在这个方法中将msg__item加载进来,
        // 然后创建一个ViewHolder实例,并将加载进来的布局传入到构造函数中
        //最后将ViewHolder实例返回
//在inflate()这个方法中,第三个参数是false,表示只让我们在父布局中声明的layout属性生效,但是不会为这个View添加父布局,
//这是因为一旦View有了父布局之后,他就不能再添加到ListView中(这也是ListView的标准写法)


        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.msg_item,parent,false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, int position){
        //该方法是将RecyclerView子项的数据进行赋值,会在每个子项被滚动到屏幕内的时候进行执行
        //通过position参数得到当前项的msg实例,然后再将数据设置到ViewHolder的Linear Layout和TextView中,
        //加入了对消息类型的判断
        Msg msg = mMsgList.get(position);
        if(msg.getType()== Msg.TYPE_RECEIVED){
            holder.leftLayout.setVisibility(View.VISIBLE);
            holder.rightLayout.setVisibility(View.GONE);
            holder.leftMsg.setText(msg.getContent());
        }else if (msg.getType()==Msg.TYPE_SEND){
            holder.leftLayout.setVisibility(View.GONE);
            holder.rightLayout.setVisibility(View.VISIBLE);
            holder.rightMsg.setText(msg.getContent());
        }
    }
    @Override
    public int getItemCount(){
        //用于告诉RecyclerView一共有多少子项,直接返回数据源的长度
        return mMsgList.size();
    }
}

6、修改MainActivity中的代码,来为RecyclerView初始化一些数据,并给发送按钮加入事件响应
==在initMsgs()方法中我们先初始化了几条数据用于在RecyclerView中显示,然后在发送按钮的事件里获取了EditText中的内容,如果内容不为空字符串 则创建出一个新的Msg对象,并将它添加到msgList列表中去,之后调用了适配器的notifyItemInserted()方法,用来通知列表有新的数据插入,这样新增的一条消息才能够在RecyclerView中显示。接着调用RecyclerView的scrollToPosition()方法将显示的数据定位到最后一行,以保证一定可以看得到最后发出的一条消息,最后调用EditText的setText()方法将输入的内容清空。

package com.example.uibestpratice;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

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

public class MainActivity extends AppCompatActivity {
    private List<Msg> msgList =  new ArrayList<>();
    private EditText inputText;
    private Button send;
    private RecyclerView msgRecyclerView;
    private MsgAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //初始化消息数据
        initMsgs();
        inputText =(EditText) findViewById(R.id.input_text);
        send = (Button) findViewById(R.id.send);
        
        //获取到RecyclerView实例
        msgRecyclerView = (RecyclerView) findViewById(R.id.msg_recycler_view);
        //随后创建了一个 LinearLayoutManager对象,并将它设置到RecyclerView当中,
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        msgRecyclerView.setLayoutManager(layoutManager);
        
        //创建了MsgAdapter 实例,并将msgList中的数据传入到MsgAdapter的构造函数中,
        adapter = new MsgAdapter(msgList);
        //调用RecyclerView的setAdapter()方法来完成适配器配置
        //此时RecyclerView和数据之间的关联就建立起来了。
        msgRecyclerView.setAdapter(adapter);
        
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = inputText.getText().toString();
                
                //如果内容不为空的字符串,则创建出一个新的Msg对象,并将它添加到msgList列表中去。
                if(!"".equals(content)){
                    Msg msg = new Msg(content,Msg.TYPE_SEND);
                    msgList.add(msg);

                    //当有新消息时,刷新RecyclerView中的显示
                    //调用适配器的notifyItemInserted()方法,用来通知列表有新的数据插入,这样新增的一条消息才能够在RecyclerView中显示
                   adapter.notifyItemInserted(msgList.size()-1);


                    //将RecyclerView定位到最后一行,以保证一定可以看得到最后发出的一条消息
                    msgRecyclerView.scrollToPosition(msgList.size()-1);
                    //清空输入框中的内容
                    inputText.setText("");
                }
            }
        });

    }
    //来为RecyclerView初始化一些数据
    public void initMsgs(){
        Msg msg1 = new Msg("hello guy",Msg.TYPE_RECEIVED);
        msgList.add(msg1);
        Msg msg2 = new Msg("hello,who is that?",Msg.TYPE_SEND);
        msgList.add(msg2);
        Msg msg3 = new Msg("This is Tom,Nice talking to you",Msg.TYPE_RECEIVED);
        msgList.add(msg3);
    }
}

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值