本文用 TextView 实现一个在手机上显示 Android 信息的工具类。比如涉及到信号的传递时,那种类似日志记录的功能。先看图:
先看布局文件的代码,注意 TextView 里面的几个属性就可以了。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp">
<EditText
android:id="@+id/edit_text"
android:layout_width="150dp"
android:layout_height="wrap_content" />
<Button
android:id="@+id/clear_log"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="清空日志"/>
<Button
android:id="@+id/add_log"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="记录日志"/>
</LinearLayout>
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fadeScrollbars="false"
android:padding="20dp"
android:scrollbars="vertical"
android:textSize="13sp" />
</LinearLayout>
接着在代码中进行设置,关注标“核心”注释处的代码,以及 addText() 方法的代码就可以了。
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText editText;
private Button addLogBtn;
private Button clearLogBtn;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
editText = (EditText)findViewById(R.id.edit_text);
addLogBtn = (Button)findViewById(R.id.add_log);
clearLogBtn = (Button)findViewById(R.id.clear_log);
//核心
textView = (TextView)findViewById(R.id.text_view);
textView.setMovementMethod(ScrollingMovementMethod.getInstance());
addLogBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String myLog = editText.getText().toString();
if(!TextUtils.isEmpty(myLog)){
addText(textView,myLog);
//editText.setText(""); //可清空 EditText 中的内容。
}
}
});
clearLogBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clearText(textView);
}
});
}
//添加日志
private void addText(TextView textView, String content) {
textView.append(content);
textView.append("\n");
int offset = textView.getLineCount() * textView.getLineHeight();
if (offset > textView.getHeight()) {
textView.scrollTo(0, offset - textView.getHeight());
}
}
//清空日志
private void clearText(TextView mTextView) {
mTextView.setText("");
}