聊天室窗口的高度室固定的,新的文字消息总是加入窗口末尾,同时窗口内部的文本整体向上滚动,窗口的大小,位置保持不变。
1.聊天室用到的属性与方法说明
XML中的属性 | 聊天室用到的设置方法 | 说明 |
gravity | setGravity | 指定文本的对齐方式,取值left|bottom,表示靠左对齐且靠下对齐 |
lines | setLines | 指定文本的行数 |
maxLines | setMaxLines | 指定文本的最大行数 |
scrollbars | 无 | 指定滚动条的方向,取值Vertical,如果不指定将不显示滚动条 |
无 | setMovementMethod | 设置文本的移动方式,可设置ScrollingMovementMethod,如果不设置将无法拉动文本 |
2.聊天室风格TextView举例
布局文件
<?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/tv"
android:layout_width="match_parent"
android:layout_height="100dp"
android:gravity="left|bottom"
android:layout_marginTop="100dp"
android:lines="8"
android:maxLines="8"
android:scrollbars="vertical"/>
<Button
android:id="@+id/bt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="添加文字"/>
</LinearLayout>
java代码中
public class MainActivity extends AppCompatActivity {
private TextView tv;
private Button bt;
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.tv);
bt = findViewById(R.id.bt);
tv.setMovementMethod(new ScrollingMovementMethod());
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tv.append("\n哈哈哈 "+simpleDateFormat.format(System.currentTimeMillis()));
int scrollAmount = tv.getLayout().getLineTop(tv.getLineCount())
- tv.getHeight();
if (scrollAmount > 0) {
tv.scrollTo(0, scrollAmount);
}else {
tv.scrollTo(0, 0);
}
}
});
}
}
这样每次按动一下按钮就会增加一条内容进入TextView中,并自动滚动到最底部。我们同样也可以手动拖动查看之前的内容。
这种风格做聊天室可能不太合理了,因为聊天室每条内容都是有头像,文字还有他们自己的样式。我认为可能两种情况使用比较合理,一种是日志实时记录显示;一种是直播的简单留言板。