2016-7-26 TextView自动下滚,以及TCP Client
TextView的设置
weight保证这个view不出显示问题
onCreate中
tcp client:
public void click_start(View view) { flag = true; new Thread() { @Override public void run() { try { if (socket == null || socket.isClosed()) socket = new Socket(ip, port); } catch (IOException e) { e.printStackTrace(); } while (flag) { try { // 发送 writer = socket.getOutputStream(); writer.write("Hello server".getBytes("utf-8")); // 接收 reader = socket.getInputStream(); int len = -1; byte[] buffer = new byte[1024]; while ((len = reader.read(buffer)) != -1) { str = new String(buffer, 0, len); runOnUiThread(new Runnable() { @Override public void run() { _tv.append("\n" + str + " | " + new Date(System.currentTimeMillis())); int offset = _tv.getLineCount() * _tv.getLineHeight(); if (offset > _tv.getHeight()) { // 更新文字时,使用View的scrollTo(int x,int y)方法 // 使其自动滚动到最后一行。 _tv.scrollTo(0, offset - _tv.getHeight()); } } }); writer.write("Hello server".getBytes("utf-8")); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } catch (IOException e) { e.printStackTrace(); } } } }.start(); } public void click_stop(View view) { flag = false; _tv.setText(""); if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } socket = null; } }
效果: