2__1.8__模拟聊天室_使用textview_先读取再拼接

activity_chat.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/tvChatTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="这是聊天室,点击和长按我试试"
android:textSize="30dp"/>

<TextView
android:id="@+id/tvChatContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:textSize="20dp"
android:layout_marginTop="20dp"
/>
</LinearLayout>

--------------------------------------------------------

ChatActivity.java

package com.example.dfby.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ChatActivity extends AppCompatActivity implements View.OnClickListener,View.OnLongClickListener {
private TextView tvChatTitle,tvChatContent;
private String[] messages={"今天天气不错","约起来","大家好啊","哇哦居然下雪了","加油"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
tvChatTitle=findViewById(R.id.tvChatTitle);
tvChatContent=findViewById(R.id.tvChatContent);
tvChatTitle.setOnClickListener(this);
tvChatContent.setOnClickListener(this);
tvChatTitle.setOnLongClickListener(this);
tvChatContent.setOnLongClickListener(this);

tvChatContent.setLines(8);
tvChatContent.setMaxLines(10);


}

@Override
public void onClick(View v) {
int index=(int)(Math.random()*10)%5;
String str=String.format("%s\n%s %s",tvChatContent.getText().toString(),new SimpleDateFormat("HH:mm:ss").format(new Date()),messages[index]);
tvChatContent.setText(str);
tvChatContent.setMovementMethod(new ScrollingMovementMethod());
}

@Override
public boolean onLongClick(View v) {
tvChatContent.setText("");
return true;
}
}

猜你喜欢

转载自www.cnblogs.com/bj-tony/p/10243523.html