根据学习笔记一完成一些代码,贴出来看看:
Notepad.java
package com.example.notepad;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
// TODO: Auto-generated Javadoc
/**
* The Class Notepad.
*/
public class Notepad extends Activity {
/** The et. */
private EditText et;
/** The Constant RECOGNIZER. */
private static final int RECOGNIZER = 1001; // Intent返回结果验证码
/** The filename. */
private String filename = "新建文档.txt"; // 保存文本时默认文件名
/** The my dialog edit text. */
private EditText myDialogEditText;
public static final String INTENAL_ACTION_1 = "com.example.notpad.Internal_1";
static Notepad activity = null;
private BroadcastReceiver bcrIntenal1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("message");
// Toast.makeText(context, "动态:" + msg, 0).show();
try {
// byteFile.writeToFile(msg);
save();
Log.v("msg",
"save in temporary file automatic (temp.txt)");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public static class LinedEditText extends EditText {
private Rect mRect;
private Paint mPaint;
// This constructor is used by LayoutInflater
public LinedEditText(Context context, AttributeSet attrs) {
super(context, attrs);
// Creates a Rect and a Paint object, and sets the style and color
// of the Paint object.
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setColor(0x800000FF);
}
public static Activity getActivity() {
return activity;
}
/**
* This is called to draw the LinedEditText object
*
* @param canvas The canvas on which the background is drawn.
*/
@Override
protected void onDraw(Canvas canvas) {
// Gets the number of lines of text in the View.
int count = getLineCount();
// Gets the global Rect and Paint objects
Rect r = mRect;
Paint paint = mPaint;
/*
* Draws one line in the rectangle for every line of text in the
* EditText
*/
for (int i = 0; i < count; i++) {
// Gets the baseline coordinates for the current line of text
int baseline = getLineBounds(i, r);
/*
* Draws a line in the background from the left of the rectangle
* to the right, at a vertical position one dip below the
* baseline, using the "paint" object for details.
*/
canvas.drawLine(r.left, baseline + 1, r.right,
baseline + 1, paint);
}
// Finishes up by calling the parent method
super.onDraw(canvas);
}
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.EditText01);
activity = this;
// 动态注册广播消息
registerReceiver(bcrIntenal1, new IntentFilter(
INTENAL_ACTION_1));
Intent serviceIntent = new Intent(Notepad.this,
MyService.class);
startService(serviceIntent);
}
public static Activity getActivity() {
return activity;
}
// public void onStart() {
// Intent intent = this.getIntent();
// System.out.println(intent.getStringExtra("data"));
// et.setText(intent.getStringExtra("data"));
// }
/*
* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
public void onResume() { // 重写onResume,防止程序stop后编辑内容丢失
super.onResume();
registerReceiver(bcrIntenal1, new IntentFilter(
INTENAL_ACTION_1));
// try {
// File file = new File("/mnt/sdcard/Notepad/temp1.txt"); // 读取临时文件,恢复上一次编辑内容
// RandomAccessFile stream = new RandomAccessFile(file, "rw");
// String s = stream.readLine();
// stream.close();
// et.setText(s);
// } catch (Exception e) {
// // TODO: handle exception
// e.printStackTrace();
// }
}
// public void onStop() {
// super.onStop();
// unregisterReceiver(bcrIntenal1);
// }
/*
* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
public void onPause() { // 编辑内容存入临时文件
super.onPause();
unregisterReceiver(bcrIntenal1);
// File file = new File("/mnt/sdcard/Notepad/temp1.txt");
// String data = et.getText().toString();
//
// try {
//
// RandomAccessFile stream = new RandomAccessFile(file, "rw");
// stream.writeBytes(data);
// stream.close();
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuItemNew:
creatNote();
return true;
case R.id.menuItemOpen:
openNote();
return true;
case R.id.menuItemSave:
saveNote();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Creat note.
*/
private void creatNote() {
et.setText("");
}
/**
* Open note.
*/
private void openNote() {
Intent list = new Intent(this, OpenNote.class);
startActivityForResult(list, RECOGNIZER);
}
/*
* (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int,
* android.content.Intent)
*/
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == RECOGNIZER && resultCode == RESULT_OK) {
String text = data.getExtras().getString("data");
et.setText(text);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void save() {
File sdcardDir = Environment
.getExternalStorageDirectory();
String path = sdcardDir.getName()
+ "/Notepad";
File f = new File(path);
String fileName = path
+ java.io.File.separator
+ "temp.txt";
java.io.BufferedWriter bw;
try {
bw = new java.io.BufferedWriter(
new java.io.FileWriter(
new java.io.File(fileName)));
String str = et.getText().toString();
bw.write(str, 0, str.length());
bw.newLine();
bw.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
/**
* Save note.
*/
private void saveNote() {
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(
R.layout.save_dialog, null);
Builder builder = new AlertDialog.Builder(Notepad.this);
builder.setView(textEntryView);
myDialogEditText = (EditText) textEntryView
.findViewById(R.id.myDialogEditText);
myDialogEditText.setText(filename);
builder.setTitle("保存");
builder.setPositiveButton(R.string.str_alert_ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
File sdcardDir = Environment
.getExternalStorageDirectory();
String path = sdcardDir.getName()
+ "/Notepad";
File f = new File(path);
File[] files = f.listFiles();
filename = myDialogEditText.getText()
.toString();
for (int i = 0; i < files.length; i++) { // 存在同名文件
File file = files[i];
// Log.v("name", file.getName().toString());
if (file.getName().toString()
.equals(filename)) {
new AlertDialog.Builder(Notepad.this)
.setTitle("文件名重复,请重新输入")
.setPositiveButton("OK", null)
.show();
}
}
String fileName = path
+ java.io.File.separator
+ myDialogEditText.getText()
.toString();
java.io.BufferedWriter bw;
try {
bw = new java.io.BufferedWriter(
new java.io.FileWriter(
new java.io.File(fileName)));
String str = et.getText().toString();
bw.write(str, 0, str.length());
bw.newLine();
bw.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
builder.setNegativeButton(R.string.str_alert_cancel, null);
builder.show();
}
}
OpenNote.java
package com.example.notepad;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
// TODO: Auto-generated Javadoc
/**
* The Class OpenNote.
*/
public class OpenNote extends Activity {
/** Called when the activity is first created. */
private ListView listview;
/** The items. */
private ArrayList<String> items = null;
/** The paths. */
private ArrayList<String> paths = null;
/** The root path. */
private String rootPath = "/"; // 根目录
/** The m path. */
private TextView mPath; // 当前路径
/** The currentpath. */
String currentpath;
/** The list items. */
private List<Map<String, Object>> listItems = null;
/* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.open_note);
init();
getFileDir(rootPath);
}
/**
* Gets the file dir.
*
* @param filePath the file path
* @return the file dir
*/
private void getFileDir(String filePath) {
mPath.setText("当前目录:" + filePath);
currentpath = filePath;
List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
items = new ArrayList<String>();
paths = new ArrayList<String>();
File f = new File(filePath);
File[] files = f.listFiles();
Map<String, Object> listItem = new HashMap<String, Object>();
if (!filePath.equals(rootPath)) {
items.add("cd /");
paths.add(rootPath);
items.add("cd ..");
paths.add(f.getParent());
listItem.put("header", R.drawable.back01);
listItem.put("name", "cd /");
listItems.add(listItem);
Map<String, Object> listItem1 = new HashMap<String, Object>();
listItem1.put("header", R.drawable.back02);
listItem1.put("name", "cd ..");
listItems.add(listItem1);
}
for (int i = 0; i < files.length; i++) {
Map<String, Object> listItem2 = new HashMap<String, Object>();
File file = files[i];
items.add(file.getName());
paths.add(file.getPath());
if (file.isDirectory()) {
listItem2.put("header", R.drawable.folder);
}
else {
String pathStr = file.getAbsolutePath();
if (pathStr
.matches("[^\\S]+(\\.avi|\\.mp4|\\.rmvb)$")) {
listItem2.put("header", R.drawable.video);
} else if (pathStr.matches("[^\\S]+(\\.asv|\\.mp3)$")) {
listItem2.put("header", R.drawable.audio);
} else if (pathStr
.matches("[^\\S]+(\\.jpg|\\.png|\\.gif)$")) {
listItem2.put("header", R.drawable.image);
} else {
listItem2.put("header", R.drawable.doc);
}
}
listItem2.put("name", file.getName());
listItems.add(listItem2);
}
String[] from = {
"header", "name"
};
int[] to = {
R.id.header, R.id.name
};
SimpleAdapter adapter = new SimpleAdapter(this, listItems,
R.layout.file_row, from, to);
listview.setAdapter(adapter);
}
/**
* Inits the.
*/
public void init() {
listview = (ListView) findViewById(R.id.file_listview);
mPath = (TextView) findViewById(R.id.current_path);
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position,
long id) {
File file = new File(paths.get(position));
if (file.canRead()) {
if (file.isDirectory()) {
getFileDir(paths.get(position));
}
else {
String data = "fail";
try {
FileInputStream stream = new FileInputStream(
paths.get(position));
StringBuffer sb = new StringBuffer();
int c;
while ((c = stream.read()) != -1) {
sb.append((char) c);
}
stream.close();
data = sb.toString();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Intent i = getIntent();
i.putExtra("data", data);
setResult(RESULT_OK, i);
finish();
}
} else {
Toast toast = Toast.makeText(OpenNote.this,
"您的权限不足!", Toast.LENGTH_LONG);
toast.show();
}
}
});
}
/* (non-Javadoc)
* @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == event.KEYCODE_BACK) {
if (currentpath == rootPath) {
File f = new File(currentpath);
getFileDir(currentpath);
}
else {
File f = new File(currentpath);
getFileDir(f.getParent());
}
}
return super.onKeyDown(keyCode, event);
}
}