簡易テキストエディタをソースコードを公開しながら作ってみる。簡易なのでテキストの管理方法とか手抜きだし、それほど難しいことをしたいわけじゃない。とりあえず作成開始。今回はテキストの表示を行うだけのアプリケーションを作成する。
まずはテキストの管理を行うクラスを作成する。とは言ってもList
package text.edit.document; import java.util.List; import java.util.ArrayList; public class TextDocument { private final List<StringBuilder> textList; public TextDocument(){ textList = new ArrayList<StringBuilder>(); textList.add(new StringBuilder()); } public void setText(String text){ for(char c : text.toCharArray()){ append(c); } } public String getText(){ StringBuilder text = new StringBuilder(textList.size() * 10); for(StringBuilder line : textList){ text.append(line).append('\n'); } return text.substring(0, text.length() - 1); } public String getLine(int index){ return textList.get(index).toString(); } public int getLineCount(){ return textList.size(); } public void append(char c){ if(c == '\n'){ textList.add(new StringBuilder()); return; } textList.get(textList.size() - 1).append(c); } }
setTextで指定された文字列をappendで1文字ずつ追加していき、appendは'\n'が来たら改行する。getLineで1行取得、getTextで全て取得、getLineCountで行数を取得する。
次に表示するクラスを作成する。android.view.Viewを継承し、setTextでテキスト設定、onDrawで描画を行っている。描画はTextDocumentから1行ずつ取ってきて、それをCanvas#drawStringで表示しているだけ
package text.edit.view; import android.view.View; import android.content.Context; import android.graphics.Color; import android.graphics.Canvas; import android.text.TextPaint; import text.edit.document.TextDocument; public class EditorView extends View{ private TextDocument document; public EditorView(Context context){ super(context); document = new TextDocument(); setBackgroundColor(Color.WHITE); } public void setText(String text){ document.setText(text); invalidate(); } @Override protected void onDraw(Canvas canvas){ TextPaint paint = new TextPaint(); paint.setTextSize(16); for(int row = 0; row < document.getLineCount(); row++){ String line = document.getLine(row); canvas.drawText(line, 0, (row + 1) * 16, paint); } } }
最後に一応Activityも載せておく
package text.edit; import android.app.Activity; import android.os.Bundle; import text.edit.view.EditorView; public class TextEditorTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EditorView editor = new EditorView(this); editor.setText("Hello\nWorld!"); setContentView(editor); } }